我從這個網站使用多個構造。缺少多個參數__construct
我修改了我的需要。
我得到致命錯誤:
Missing argument 3 for ChildClass::__construct2()
和鏈接錯誤...
Missing argument 4 for ChildClass::__construct2()
Missing argument 5 for ChildClass::__construct2()
Undefined variable: c
Undefined variable: d
而且兩者構造具有相同代碼的一部分。我怎樣才能把它放在常見的__construct中。
$arr = array (
"key1" => "val1",
"key2" => "val2"
);
$demo = new Demo("stack", $arr);
class ParentClass {
function __construct($var1 = "1", $var2 = "2"){
// distinctly different code
}
}
class ChildClass extends ParentClass {
function __construct(){
$a = func_get_args();
$i = func_num_args();
if (method_exists($this,$f='__construct'.$i)) {
call_user_func_array(array($this,$f),$a);
}
}
function __construct1($a, array $e) {
$this->ex = $a;
$this->ex3 = $e['key1'];
$this->ex4 = $e['key2'];
}
function __construct2($a, $b, $c, $d, array $e) {
$this->ex = $a + 1 - $v + $c; //example
$this->ex2 = $d;
$this->ex3 = $e['key1'];
$this->ex4 = $e['key2'];
}
}
而這兩個構造函數都有部分相同的代碼。我怎樣才能把它放在常見的__construct中。
謝謝。
你'ChildClass'構造是無效的:它打破了繼承合同。也不要在自己的方法名中使用'__'前綴,它們只能用於魔術方法(構造函數,析構函數,設置方法,獲取方,...) –