Calling Child Class Functions from Parent Class
In PHP, it's possible to call a function from a child class within a parent class, but it requires careful planning.
Consider the following code example:
<code class="php">class whale { ... } class fish extends whale { ... }</code>
In this example, we have a whale class and a fish class that inherits from it. The goal is to call the test() function from the fish class within the myfunc() function of the whale class.
Solution: Use Abstract Classes
To achieve this, we can leverage abstract classes. An abstract class enforces the implementation of certain methods in its child classes.
<code class="php">abstract class whale { function __construct() { ... } function myfunc() { $this->test(); } abstract function test(); }</code>
In the updated whale class, we now declare myfunc() and test() as abstract methods. myfunc() will call test(), which needs to be implemented in the child class.
<code class="php">class fish extends whale { function __construct() { parent::__construct(); } function test() { echo "So you managed to call me !!"; } }</code>
In the fish class, we provide an implementation for test(). This ensures that the abstract requirements of the parent class are met.
With this setup, we can now call the test() function from fish within myfunc() of the whale class.
<code class="php">$fish = new fish(); $fish->test(); // Output: So you managed to call me !! $fish->myfunc(); // Output: So you managed to call me !!</code>
By using abstract classes, we enforce proper inheritance and ensure that child classes implement the required methods. This allows us to call child class functions from parent classes seamlessly.
The above is the detailed content of How to Call Child Class Functions from Parent Class in PHP Using Abstract Classes?. For more information, please follow other related articles on the PHP Chinese website!