Search code examples
phpinheritanceconstructordefault-constructor

Missing Argument in for multiple __construct


I use multiple construct from this site.

I modified it for my needs.

I get fatal errors:

Missing argument 3 for ChildClass::__construct2() 

and chained errors...

Missing argument 4 for ChildClass::__construct2() 
Missing argument 5 for ChildClass::__construct2() 
Undefined variable: c 
Undefined variable: d 

And both constructors have part of identical code. How can I put it in common __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'];
    }
}

And both constructors have part of identical code. How can I put it in common __construct.

thanks.


Solution

  • The number specified after __construct tells how many parameter it will except . You specified 2 after __construct but you are giving it 5 parameters because of which it is giving the error. Change 2 to 5.Also rename __construct1 to __construct2 Use the code below

    $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'];
        }
    }
    

    Hope this helps you