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

前端 未结 7 1210
-上瘾入骨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:45

    My way of doing it (tested in PHP 7.1):

    class ParentClass {
        public function __construct(...$args) {
            print 'Parent: ' . count($args) . PHP_EOL;
        }
    }
    
    class ChildClass extends ParentClass {
        public function __construct(...$args) {
            parent::__construct(...$args);
            print 'Child: ' . count($args). PHP_EOL;
        }
    }
    
    $child = new ChildClass(1, 2, 3, new stdClass);
    
    //Output: 
    //Parent: 4
    //Child: 4
    

    Test it https://3v4l.org/csJ68

    In this case, the parent and the child have the same constructor signature. It also works if you want to unpack your arguments in the parent constructor:

    class ParentClass {
        public function __construct($a, $b, $c, $d = null) {
            print 'Parent: ' . $a .  $b .  $c . PHP_EOL;
        }
    }
    
    class ChildClass extends ParentClass {
        public function __construct(...$args) {
            parent::__construct(...$args);
        }
    }
    
    $child = new ChildClass(1, 2, 3);
    
    //Output: Parent: 123
    

    Test it https://3v4l.org/JGE1A

    It is also worth noticing that in PHP >= 5.6 you can enforce types for variadic functions (scalar types in PHP >= 7):

    class ParentClass {
        public function __construct(DateTime ...$args) {
            //Do something
        }
    }
    
    0 讨论(0)
提交回复
热议问题