In PHP, a common task is invoking functions defined in child classes from within parent classes. Consider the following example:
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 !!";
}
}
One solution is to utilize abstract classes, which define essential functions that must be implemented by inheriting classes. Here's a modified code:
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();
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.
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