Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 241
none Avatar asked Oct 21 '09 20:10

none


People also ask

How do you call a method from child class to parent class in PHP?

To call the constructor of the parent class from the constructor of the child class, you use the parent::__construct(arguments) syntax. The syntax for calling the parent constructor is the same as a regular method.

What does parent __construct () do?

We can do this by using the special function call parent::__construct(). The "parent" part means "get the parent of this object, and use it", and the __construct() part means "call the construct function", of course. So the whole line means "get the parent of this object then call its constructor".

How do you call a constructor of parent class in child class?

In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private). $obj = new OtherSubClass();

Does child inherit parent constructor?

If the parent class has a constructor, all its children classes will inherit that constructor.


2 Answers

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()); } 
like image 169
Andy Avatar answered Oct 02 '22 10:10

Andy


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

$args = func_get_args(); call_user_func_array(array($this, 'parent::__construct'), $args); 
like image 44
soulmerge Avatar answered Oct 02 '22 12:10

soulmerge