PHP实现多个构造函数的最佳方法
|
PHP实现多个构造函数的最佳方法: class Student { public function __construct() { // allocate your stuff } public static function withID( $id ) { $instance = new self(); $instance->loadByID( $id ); return $instance; } public static function withRow( array $row ) { $instance = new self(); $instance->fill( $row ); return $instance; } protected function loadByID( $id ) { // do query $row = my_awesome_db_access_stuff( $id ); $this->fill( $row ); } protected function fill( array $row ) { // fill all properties from array } } ?> 然后,如果我想要一个我知道ID的学生: $student = Student::withID( $id ); 或者,如果我有一个db行数组: $student = Student::withRow( $row ); 从技术上讲,你不是构建多个构造函数,只是构造静态辅助方法,但是你可以通过这种方式避免构造函数中的大量意大利面条代码。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
