2012-02-25 3 views
4

これは構成された例であり、多くのパラメータがある場合にははるかに役立ちます。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; 
} 

これができない場合は、良い方法はありますか?

+0

@phpdev同様の考え方ですが、いいえ。同じクラスの別のコンストラクタを呼び出します。ああ、あなたは消えてしまったよ、まあ今私はちょっと気分が悪い... –

答えて

6
私はあなたがそれらを呼び出すしたい任意の他/代替コンストラクタ/工場や名前の使用しているだろうそのために

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); 

1つの標準的なコンストラクタがあるはずですが、しかし、あなたが持つことができる一例として、コンビニエンスラッパーと同じくらい多くの代替コンストラクターがすべて標準的なコンストラクターを参照します。あるいは、普通のコンストラクタでは設定しない代替コンストラクタで代替値を設定することもできます:

class Foo { 

    protected $bar = 'default'; 

    public static function withBar($bar) { 
     $foo = new self; 
     $foo->bar = $bar; 
     return $foo; 
    } 

} 
1

これはまったく同じではありませんが、コンストラクタの引数の数を操作したり、数えたり、型をチェックして対応する関数を呼び出すことができます。

class MultipleConstructor { 
    function __construct() { 
    $args = func_get_args(); 
    $construct = '__construct' . func_num_args(); 
    if (method_exists($this, $construct)) 
     call_user_func_array(array($this, $construct), $args); 
    } 

    private function __construct1($var1) 
    { 
     echo 'Constructor with 1 argument: ' . $var1; 
    } 

    private function __construct2($var1, $var2) 
    { 
     echo 'Constructor with 2 arguments: ' . $var1 . ' and ' . $var2; 
    } 

} 

$pt = new MultipleConstructor(1); 
$pt = new MultipleConstructor(2,3); 
+0

興味深いことに、 '__construct'では、私の例ではすべて「同じ/重複する」パラメータ、' name'を設定することができました。 '__constructN'では" extra/different "パラメータを設定します。それはうまくいくかもしれない。 –

関連する問題