PHP: How to Pass child class __construct() arguments to parent::__construct()?

前端 未结 7 1209
-上瘾入骨i
-上瘾入骨i 2020-12-14 00:17

I have a class in PHP like so:

class ParentClass {
    function __construct($arg) {
        // Initialize a/some variable(s) based on $arg
    }
}


        
相关标签:
7条回答
  • 2020-12-14 00:22

    Check out these functions on php.net:

    func_get_args
    func_num_args
    

    Also, if you want to make an optional argument, you can do this:

    class ParentClass {
        function __construct($arg, $arg2="Default Value") {
            // Initialize a/some variable(s) based on $arg
        }
    }
    
    0 讨论(0)
  • 2020-12-14 00:28
    parent::__construct( func_get_args() );
    
    0 讨论(0)
  • 2020-12-14 00:32

    Yeah, it's pretty bad practice to make a child class that uses different constructor arguments from the parent. Especially in a language like PHP where it's poorly supported.

    Of course, the generic way to pass a set of "whatever arguments we might ever want" in PHP is to pass a single argument consisting of an array of configuration values.

    0 讨论(0)
  • 2020-12-14 00:34

    if you get php nested limit error, try this:

    $args = func_get_args();
    call_user_func_array(array('parent', '__construct'), $args);
    
    0 讨论(0)
  • 2020-12-14 00:35

    There is something like this in php, though a bit verbose:

    $args = func_get_args();
    call_user_func_array(array($this, 'parent::__construct'), $args);
    
    0 讨论(0)
  • 2020-12-14 00:42

    This can be done in PHP >= 5.6 without call_user_func_array() by using the ... (splat) operator:

    public function __construct()
    {
        parent::__construct(...func_get_args());
    }
    
    0 讨论(0)
提交回复
热议问题