I am extending one of the SPL (Standard PHP Library) classes and I am unable to call the parent\'s constructor. Here is the error I am getting:
Fatal erro
If you want to call the constructor of the nearest ancestor, you can loop through the ancestors with class_parents and check with method_exists if it has a constructor. If so, call the constructor; if not, continue your search with the next nearest ancestor. Not only do you prevent overriding the parent's constructor, but also that of other ancestors (in case the parent doesn't have a constructor):
class Queue extends SplQueue {
public function __construct() {
echo 'before';
// loops through all ancestors
foreach(class_parents($this) as $ancestor) {
// check if constructor has been defined
if(method_exists($ancestor, "__construct")) {
// execute constructor of ancestor
eval($ancestor."::__construct();");
// exit loop if constructor is defined
// this avoids calling the same constructor twice
// e.g. when the parent's constructor already
// calls the grandparent's constructor
break;
}
}
echo 'I have made it after the parent constructor call';
}
}
For code reuse, you could also write this code as a function that returns the PHP code to be eval
ed:
// define function to be used within various classes
function get_parent_construct($obj) {
// loop through all ancestors
foreach(class_parents($obj) as $ancestor) {
// check if constructor has been defined
if(method_exists($ancestor, "__construct")) {
// return PHP code (call of ancestor's constructor)
// this will automatically break the loop
return $ancestor."::__construct();";
}
}
}
class Queue extends SplQueue {
public function __construct() {
echo 'before';
// execute the string returned by the function
// eval doesn't throw errors if nothing is returned
eval(get_parent_construct($this));
echo 'I have made it after the parent constructor call';
}
}
// another class to show code reuse
class AnotherChildClass extends AnotherParentClass {
public function __construct() {
eval(get_parent_construct($this));
}
}