これは作り上げられた例であり、パラメータが多い場合にはるかに役立ちます。
これにより、呼び出し元はまたはのいずれ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;
}
これが不可能な場合、良い代替手段は何ですか?