2012-02-25 68 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類似的想法,但沒有。調用同一個類的另一個構造函數。哦,你走了,現在我只是覺得尷尬...... – 2012-02-25 03:56:32

回答

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

應該有一個規範的構造函數,但你可以有儘可能多的替代構造函數作爲便利包裝,所有這些都引用了規範。或者你也可以在你不正規人們通常設置這些替代構造設置可選值爲:

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」參數。這可以工作。 – 2012-02-25 03:59:23

相關問題