3 回答

TA貢獻1862條經驗 獲得超6個贊
Kris的解決方案確實很棒,但我發現工廠和流利的風格更好地融合在一起:
<?php
class Student
{
protected $firstName;
protected $lastName;
// etc.
/**
* Constructor
*/
public function __construct() {
// allocate your stuff
}
/**
* Static constructor / factory
*/
public static function create() {
$instance = new self();
return $instance;
}
/**
* FirstName setter - fluent style
*/
public function setFirstName( $firstName) {
$this->firstName = $firstName;
return $this;
}
/**
* LastName setter - fluent style
*/
public function setLastName( $lastName) {
$this->lastName = $lastName;
return $this;
}
}
// create instance
$student= Student::create()->setFirstName("John")->setLastName("Doe");
// see result
var_dump($student);
?>

TA貢獻1784條經驗 獲得超7個贊
我可能會做這樣的事情:
<?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 );
或者,如果我有數據庫行的數組:
$student = Student::withRow( $row );
從技術上講,您不是在構建多個構造函數,而只是在構建靜態輔助方法,而是通過這種方式避免在構造函數中使用大量意大利面條式代碼。

TA貢獻1811條經驗 獲得超5個贊
PHP是一種動態語言,因此您不能重載方法。您必須像這樣檢查參數的類型:
class Student
{
protected $id;
protected $name;
// etc.
public function __construct($idOrRow){
if(is_int($idOrRow))
{
$this->id = $idOrRow;
// other members are still uninitialized
}
else if(is_array($idOrRow))
{
$this->id = $idOrRow->id;
$this->name = $idOrRow->name;
// etc.
}
}
- 3 回答
- 0 關注
- 811 瀏覽
添加回答
舉報