缺少多个__construct的参数

时间:2015-01-13 11:54:49

标签: php inheritance constructor default-constructor

我使用此网站的多个构造。

我根据自己的需要修改了它。

我得到了致命的错误:

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。

感谢。

2 个答案:

答案 0 :(得分:0)

这是因为__construct2中的2表示它需要2个参数,但它需要5.将名称更改为__construct5

要将相同的代码放在一个地方,请将它从两个构造函数调用的单独方法,完整代码:

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 __construct2( $a, array $e ) { // rename method: 1 => 2
        $this->ex = $a;

        $this->setE($e);
    }

    function __construct5( $a, $b, $c, $d, array $e ) { // rename method: 2 => 5
        $this->ex = $a + 1 - $v + $c; //example
        $this->ex2 = $d;

        $this->setE($e);
    }

    private function setE(array $e) {
        $this->ex3 = $e['key1'];
        $this->ex4 = $e['key2'];
    }
}

答案 1 :(得分:0)

__construct之后指定的数字表示它将包含多少参数。你在__construct之后指定了2,但是你给它5个参数,因为它给出了错误。将2更改为5.还要将__construct1重命名为__construct2使用下面的代码

$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 __construct2( $a, array $e ) { 
    $this->ex = $a;

    $this->setE($e);
}
    function __construct5( $a, $b, $c, $d, array $e ) {
        $this->ex = $a + 1 - $v + $c; //example
        $this->ex2 = $d;

        $this->ex3 = $e['key1'];
        $this->ex4 = $e['key2'];
    }
}

希望这有助于你