PHP: Accessing Child Class Methods from a Parent Class
Often, when working with inheritance in PHP, developers encounter the need to access functions from a child class within the parent class. This can be achieved through a powerful mechanism: abstract classes.
Consider the example code:
<code class="php">class whale { function __construct() { // some code here } function myfunc() { // how do i call the "test" function of fish class here?? } } class fish extends whale { function __construct() { parent::__construct(); } function test() { echo "So you managed to call me !!"; } }</code>
To access the "test" function from within the "whale" class, we can declare the parent class as abstract and define an abstract method corresponding to the child class function.
<code class="php">abstract class whale { function __construct() { // some code here } function myfunc() { $this->test(); } abstract function test(); } class fish extends whale { function __construct() { parent::__construct(); } function test() { echo "So you managed to call me !!"; } }</code>
Now, any class inheriting from "whale" will be forced to implement the "test" method. This ensures that all child classes have access to the functionality provided by the abstract method.
By implementing this approach, you can access child class functions from within the parent class, enabling a flexible and extensible inheritance model in PHP.
The above is the detailed content of How to Access Child Class Methods from a Parent Class in PHP?. For more information, please follow other related articles on the PHP Chinese website!