PHP 中的多個建構子
PHP 不允許在一個類別中使用多個具有不同參數簽章的建構子。當不同的場景需要不同的初始化過程時,這就帶來了挑戰。
一種方法是定義兩個建構子方法:
class Student { public function __construct($id) { $this->id = $id; } public function __construct(array $row_from_database) { $this->id = $row_from_database['id']; $this->name = $row_from_database['name']; } }
但是,這個方法違反了 PHP 的建構子語法規則。
為了規避此限制,常見的解決方案是建立靜態工廠方法:
class Student { public function __construct() { // Allocate resources here } public static function withID($id) { $student = new self(); $student->id = $id; return $student; } public static function withRow(array $row) { $student = new self(); $student->id = $row['id']; $student->name = $row['name']; return $student; } }
使用這種技術,透過靜態方法而不是建構子來執行初始化:
$studentWithID = Student::withID(42); $studentWithRow = Student::withRow(['id' => 42, 'name' => 'John']);
靜態工廠方法提供了一種靈活且可維護的方式來解決多個初始化場景,同時遵循PHP的類別設計原則。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3