多个 __construct 中缺少参数

Missing Argument in for multiple __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.

谢谢。

因为__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'];
    }
}

__construct 后指定的数字表示除 . 之外的参数数量。您在 __construct 之后指定了 2,但您给了它 5 个参数,因此它给出了错误。将 2 更改为 5.Also 将 __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'];
    }
}

希望对您有所帮助