我可能会做这样的事情:
<?phpclass 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 );
或者,如果我有数据库行的数组:
$student = Student::withRow( $row );
从技术上讲,您不是在构建多个构造函数,而只是在构建静态辅助方法,而是通过这种方式避免在构造函数中使用大量意大利面条式代码。



