I have the following two classes.
class Settings
{
function __CONSTRUCT()
{
echo "Settings Construct";
}
}
class PageManager extends Settings
{
function __CONSTRUCT()
{
echo "PageManager Construct";
}
}
$page = new PageManager();
I thought that would work fine, but it only runs PageManager's constructor. I'm assuming it's because I override the Setting's constructor. Is there some way I can call the parent's constructor as well?
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.
The fact that PHP always calls the "nearest" constructor, that is if there is no child constructor it will call the parent constructor and not the grandparent constructor, means that we need to call the parent constructor ourselves. We can do this by using the special function call parent::__construct().
PHP - The __construct Function A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!
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.
Just call it using parent::
/* Settings */
class Settings{
function __CONSTRUCT(){
echo "Settings Construct";
}
}
/* PageManager */
class PageManager extends Settings{
function __CONSTRUCT(){
parent::__CONSTRUCT();
echo "PageManager Construct";
}
}
Have a look at the manual(Constructors and Destructors)!
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