jb.*_*jb. 4 php constructor constructor-chaining
这是一个组成的例子,当有很多参数时它会变得更有用.
这会让来电者使用new Person("Jim", 1950, 10, 2)或new Person("Jim", datetimeobj).我知道可选参数,这不是我在这里寻找的.
在C#我可以这样做:
public Person(string name, int birthyear, int birthmonth, int birthday)
:this(name, new DateTime(birthyear, birthmonth, birthday)){ }
public Person(string name, DateTime birthdate)
{
this.name = name;
this.birthdate = birthdate;
}
Run Code Online (Sandbox Code Playgroud)
我可以在PHP中做类似的事情吗?就像是:
function __construct($name, $birthyear, $birthmonth, $birthday)
{
$date = new DateTime("{$birthyear}\\{$birthmonth}\\{$birthyear}");
__construct($name, $date);
}
function __construct($name, $birthdate)
{
$this->name = $name;
$this->birthdate = $birthdate;
}
Run Code Online (Sandbox Code Playgroud)
如果这是不可能的,那么什么是好的选择呢?
为此,我将使用命名/替代构造函数/工厂或其他任何你想要调用它们的东西:
class Foo {
...
public function __construct($foo, DateTime $bar) {
...
}
public static function fromYmd($foo, $year, $month, $day) {
return new self($foo, new DateTime("$year-$month-$day"));
}
}
$foo1 = new Foo('foo', $dateTimeObject);
$foo2 = Foo::fromYmd('foo', 2012, 2, 25);
Run Code Online (Sandbox Code Playgroud)
应该有一个规范的构造函数,但是你可以拥有尽可能多的替代构造函数,这些构造函数都是方便的包装器,它们都引用了规范的构造函数.或者,您可以在通常不在常规构造函数中设置的这些替代构造函数中设置替代值:
class Foo {
protected $bar = 'default';
public static function withBar($bar) {
$foo = new self;
$foo->bar = $bar;
return $foo;
}
}
Run Code Online (Sandbox Code Playgroud)