PHP クラスに、固有の引数シグネチャを持つ 2 つの __construct 関数を配置することはできません。次のようにします。
class Student
{
protected $id;
protected $name;
// etc.
public function __construct($id){
$this->id = $id;
// other members are still uninitialized
}
public function __construct($row_from_database){
$this->id = $row_from_database->id;
$this->name = $row_from_database->name;
// etc.
}
}
PHP でこれを行う最良の方法は何ですか?
ベストアンサー1
おそらく次のようなことをするでしょう:
<?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 );
技術的には、複数のコンストラクターを構築するのではなく、静的ヘルパー メソッドだけを構築しますが、この方法ではコンストラクター内の多くのスパゲッティ コードを回避できます。