In PHP, a common task is invoking functions defined in child classes from within parent classes. Consider the following example:
<code class="php">class whale { public function __construct() { // some code here } public function myfunc() { // How do I call the "test" function of the fish class here? } } class fish extends whale { public function __construct() { parent::__construct(); } public function test() { echo "So you managed to call me !!"; } }</code>
One solution is to utilize abstract classes, which define essential functions that must be implemented by inheriting classes. Here's a modified code:
<code class="php">abstract class whale { public function __construct() { // some code here } public function myfunc() { $this->test(); } abstract public function test(); } class fish extends whale { public function __construct() { parent::__construct(); } public function test() { echo "So you managed to call me !!"; } } $fish = new fish(); $fish->test(); $fish->myfunc();</code>
With this modification, you can invoke the test function of the fish class from the myfunc function of the whale class by calling $this->test(). This approach ensures that child classes must implement the test function.
The above is the detailed content of How to Call Functions of Child Classes from Parent Classes in PHP?. For more information, please follow other related articles on the PHP Chinese website!