PHP: How to call function of a child class from parent class
That's what abstract classes are for. An abstract class basically says: Whoever is inheriting from me, must have this function (or these functions).
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 !!";
}
}
$fish = new fish();
$fish->test();
$fish->myfunc();
Okay, this answer is VERY late, but why didn't anybody think of this?
Class A{
function call_child_method(){
if(method_exists($this, 'child_method')){
$this->child_method();
}
}
}
And the method is defined in the extending class:
Class B extends A{
function child_method(){
echo 'I am the child method!';
}
}
So with the following code:
$test = new B();
$test->call_child_method();
The output will be:
I am a child method!
I use this to call hook methods which can be defined by a child class but don't have to be.