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

0

Issue

I have a class in PHP like so:

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

It has a child class, as such:

class ChildClass extends ParentClass {
    public function __construct($arg) {
        // Let the parent handle construction. 
        parent::__construct($arg); 
    }
}

What if, for some reason, the ParentClass needs to change to take more than one optional argument, which I would like my Child class to provide "just in case"? Unless I re-code the ChildClass, it will only ever take the one argument to the constructor, and will only ever pass that one argument.

Is this so rare or such a bad practice that the usual case is that a ChildClass wouldn’t need to be inheriting from a ParentClass that takes different arguments?

Essentially, I’ve seen in Python where you can pass a potentially unknown number of arguments to a function via somefunction(*args) where ‘args’ is an array/iterable of some kind. Does something like this exist in PHP? Or should I refactor these classes before proceeding?

Solution

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

$args = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $args);

Answered By – soulmerge

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More