4

これは作り上げられた例であり、パラメータが多い場合にはるかに役立ちます。

これにより、呼び出し元はまたはのいずれ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;
}

これが不可能な場合、良い代替手段は何ですか?

4

2 に答える 2

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

}
于 2012-02-25T09:41:08.067 に答える
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);
于 2012-02-25T03:54:40.637 に答える