Is it possible to call function from parent class directly in PHP
I have
class P {
function fun() {
echo "P";
}
}
class Ch {
function fun() {
echo "Ch";
}
}
$x = new Ch();
How to call parent function fun from $x? Is it possible to do it directly or I h开发者_StackOverflow中文版ave to write:
function callParent {
parent::fun();
}
Simple... don't have a method of the same name in the child, in which case the parent method will be inherited by the child, and a call to $x->fun() will call the inherited method.
Assuming your code is actually meant to be this :
class P {
function fun() {
echo "P";
}
}
class Ch extends P {
function fun() {
echo "Ch";
}
function callParent{
parent::fun();
}
}
$x = new Ch();
you indeed have to use parent::fun() to call P::fun.
This might be useful in case you're overriding a method which must be called in order for the parent class to properly be initialized, for example.
Like:
class Parent {
function init($params) {
// some mandatory code
}
}
class Child extends Parent {
function init($params) {
parent::init();
// some more code
}
}
精彩评论