这是一个虚构的例子,当有很多参数时它会变得更加有用。
这将让调用者使用new Person("Jim", 1950, 10, 2)
or 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;
}
我可以在 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;
}
如果这不可能,有什么好的选择?