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 have to write:
function callParent {
parent::fun();
}
简单...在子级中没有同名的方法,在这种情况下,父级方法将被子级继承,对$ x-> fun()的调用将调用继承的方法。
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.