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:
class whale { ... }
class fish extends whale { ... }
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.
abstract class whale {
function __construct() { ... }
function myfunc() { $this->test(); }
abstract function test();
}
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.
class fish extends whale {
function __construct() { parent::__construct(); }
function test() { echo "So you managed to call me !!"; }
}
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.
$fish = new fish();
$fish->test(); // Output: So you managed to call me !!
$fish->myfunc(); // Output: So you managed to call me !!
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3