[英]parent::method() - calling non static method
I don't understand the concept of calling a parent method in PHP. 我不理解在PHP中调用父方法的概念。 The parent method is not static, yet it is called statically - normally PHP would throw an error/warning. 父方法不是静态的,但它是静态调用的 - 通常PHP会抛出错误/警告。
Question is, is this a quirk from PHP, or is this how it should be in OOP? 问题是,这是来自PHP的怪癖,还是它应该如何在OOP中?
Taking the example from php.net: 以php.net为例:
<?php
class A {
function example() {
echo "I am A::example() and provide basic functionality.<br />\n";
}
}
class B extends A {
function example() {
echo "I am B::example() and provide additional functionality.<br />\n";
parent::example();
}
}
$b = new B;
// This will call B::example(), which will in turn call A::example().
$b->example();
?>
http://php.net/manual/en/keyword.parent.php http://php.net/manual/en/keyword.parent.php
In PHP 5, calling non-static methods statically generates an E_STRICT level warning. 在PHP 5中,静态调用非静态方法会生成E_STRICT级别警告。
http://php.net/manual/en/language.oop5.static.php http://php.net/manual/en/language.oop5.static.php
If you will look at the definition of static method you will see: 如果你看一下静态方法的定义,你会看到:
So we can take this argument as an excuse for PHP . 所以我们可以把这个论点作为PHP的借口。 By the way, in C++ it is done the same way. 顺便说一句,在C ++中它以相同的方式完成。
But there are other languages, where it is done like you said. 但是还有其他语言,就像你说的那样。 For example, in JAVA , the parent method called like super.printMethod();
例如,在JAVA中 ,父方法称为super.printMethod();
, in C# , it is done like base.printMethod()
. 在C#中 ,它就像base.printMethod()
。
So in PHP it might be done for the parser simplicity, as they will need a specific edge case for such invocation parent->printMethod()
. 因此在PHP中可能会为解析器的简单性做好准备,因为对于这样的调用parent->printMethod()
,它们需要特定的边缘情况。
That notification means that you can't call a non-statically defined method as static, but the call you did inside the method is not a static call, but a call to the parent class. 该通知意味着您不能将非静态定义的方法称为静态,但您在方法内执行的调用不是静态调用,而是对父类的调用。
So this call will throw the E_STRICT warning: 所以这个调用将抛出E_STRICT警告:
$b = new B;
$b::example();
but your example will not 但你的例子不会
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.