In PHP, the base class constructor can be called within the derived class constructor using the parent::__construct() syntax. This ensures that a derived class can leverage or extend the functionality of a base class without altering it.
For example, when creating a derived class that adds new attributes, invoking the parent constructor ensures proper initialization, as shown below:
<?php
// Define the base class 'ParentClass'
class ParentClass {
protected $value;
// Constructor to initialize 'value' attribute
public function __construct($value) {
$this->value = $value;
}
}
// Define the derived class 'ChildClass'
class ChildClass extends ParentClass { // ChildClass inherits from ParentClass
private $additional_value;
// Constructor to initialize 'value' and 'additional_value'
public function __construct($value, $additional_value) {
parent::__construct($value);
$this->additional_value = $additional_value;
}
// Method to display the values
public function display() {
echo "Value: " . $this->value . "\nAdditional Value: " . $this->additional_value . "\n";
}
}
// Create an instance of 'ChildClass' and display its values
$child_class = new ChildClass("value", "additional_value");
$child_class->display();
// Value: value
// Additional Value: additional_value
?>
These examples illustrate how calling the base class constructor in PHP promotes modular and efficient inheritance by enabling derived classes to expand upon existing functionalities cleanly.