您不能在PHP类中放置两个带有唯一参数签名的__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.
}
}
Run Code Online (Sandbox Code Playgroud)
在PHP中执行此操作的最佳方法是什么?
我回答了一个问题(链接),我在另一个类的构造函数中使用了新对象的创建,这里是示例:
class Person {
public $mother_language;
function __construct(){ // just to initialize $mother_language
$this->mother_language = new Language('English');
}
Run Code Online (Sandbox Code Playgroud)
我收到了用户"Matija"(他的个人资料)的评论,他写道:你永远不应该在对象consturctor中实例化一个新对象,应该从外部推送依赖,所以使用这个类的人都知道这个类依赖于什么!
一般来说,我同意这一点,我理解他的观点.
但是,我过去常常这样做,例如:
ArrayAccess接口)的对象),这个类将用于另一个类,具有这样的列表对象,DateTime对象,include(或自动加载)依赖类,一个应该没有错误的问题,因为依赖对象可以是非常大的数,将它们全部传递给类构造函数可能会很长而且不清楚,例如
$color = new TColor('red'); // do we really need these lines?
$vin_number = new TVinNumber('xxx');
$production_date = new TDate(...);
...
$my_car = new TCar($color, $vin_number, $production_date, ...............);
Run Code Online (Sandbox Code Playgroud)因为我在Pascal"出生",然后在Delphi,我有一些习惯.在Delphi(以及FreePascal作为其竞争对手)中,这种做法经常发生.例如,有一个TStrings类处理字符串数组,并且存储它们不使用arrays而是另一个类TList,它提供了一些有用的方法,而TStrings只是某种类型的接口.该TList对象是私有声明的,并且不能从外部访问,但是getter和setter TStrings.
请解释一下,避免在构造函数中创建对象真的很重要吗?
我已经阅读了这个讨论, …