[英]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? 如何从$ x调用父函数fun? 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. 您确实必须使用parent :: fun()来调用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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.