這是一個製作的例子,當有很多參數時它變得更有用。是否有可能在PHP中鏈式重載構造函數?
這會讓主叫方使用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;
}
我可以做在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;
}
如果這是不可能的,那麼有什麼好的選擇?
@phpdev類似的想法,但沒有。調用同一個類的另一個構造函數。哦,你走了,現在我只是覺得尷尬...... – 2012-02-25 03:56:32