これは構成された例であり、多くのパラメータがある場合にははるかに役立ちます。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同様の考え方ですが、いいえ。同じクラスの別のコンストラクタを呼び出します。ああ、あなたは消えてしまったよ、まあ今私はちょっと気分が悪い... –