額外的參數考慮以下情況:處理在PHP
class Factory {
private $x = 1;
private $y = 2;
private $z = 3;
public function create(string $instance) {
return new $instance($this->x, $this->y, $this->z);
}
}
class A {
private $x;
public function __construct ($x) {
$this->x = $x;
}
public function display() {
echo "<pre>$this->x</pre>";
}
}
class B {
private $x;
private $y;
private $z;
public function __construct ($x, $y, $z) {
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
public function display() {
echo "<pre>$this->x</pre>";
echo "<pre>$this->y</pre>";
echo "<pre>$this->z</pre>";
}
}
$factory = new Factory;
$a = $factory->create("A");
$a->display();
$b = $factory->create("B");
$b->display();
正如你所看到的,工廠將始終提供3 arguments
時,它會創建一個新的實例。但是在class A
中,構造函數只需要1 argument
。由於php沒有通常的方法重載,所以這不會導致問題。但爲了安全起見,我要補充的參數列表參數爲class A
的contructor
是這樣的:
public function __construct ($x, ... $ignore) { ... }
趕上那些無謂的爭論,因爲我知道它每次會得到這些額外的參數。還是現有的代碼是足夠的?
嘗試使用http://php.net/manual/en/function.func-get-args.php爲類A,如果你需要參數 - 如果不能保持原樣。同樣在你的工廠中,你應該使用類的名字而不是變量,如果你把'a'而不是'A'會發生什麼? Imho在建立你的班級之前最好檢查一下。 – Edwin
你會用'$ ignore'做什麼? –
你可以使用func_num_args來驗證參數的數量來處理它http://php.net/manual/en/function.func-num-args.php –