I have this code:
class A {
var $arr = array();
function __construct($para) {
echo 'Not called';
}
}
class B extends A {
function __construct() {
$arr[] = 'new Item';
}
}
And as B has its own constructor construct($para) of A never gets called.
Now I could call parent::__construct($para) but then class B would need to be aware of the parameters class A needs.
I would prefer this:
class A {
var $arr = array();
function __construct($para) {
echo 'Not called';
}
}
class B extends A {
function __construct() {
parent::__construct(); // With the parameters class B was created.
// Additional actions that do not need direct access to the parameters
$arr[] = 'new Item';
}
}
Would something like that work?
I don't like the fact, that all classes that extend class A would need to define a new constructor, once class A changes its parameters, where all I want them to do is call the constructor of class A like when class B does not overwrite it with an own __construct() method.
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();
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.
For calling the constructor of a parent class we can use the super keyword. The super() method from the constructor method is used for the invocation of the constructor method of the parent class to get access to the parent's properties and methods.
To call the parent class method, we need to use super keyword.
There is a way to do this almost exactly like you originally described it, by using the call_user_func_array()
and func_get_args()
functions:
class B extends A {
function __construct() {
// call the parent constructor with whatever parameters were provided
call_user_func_array(array('parent', '__construct'), func_get_args());
// Additional actions that do not need direct access to the parameters
$arr[] = 'new Item';
}
}
While it makes an interesting exercise, I personally would not recommend actually using this - I think using a separate init()
method is a much better design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With