Calling non-static methods statically! ! This is unimaginable in java and c#, and it is absolutely impossible. Such errors will be pointed out at the compilation stage in these languages. But what about dynamic languages like php? First of all, there is no syntax error in this. php -l cannot find the error. What if it runs?
Look at an example first
Looking at this result, there are several things worth noting:
The first is myClass::getName(), which is a static function call
But look at the getName() function of myClass, it is not a static function.
Secondly return the structure
First return PHP Strict Standards Error. People who are familiar with PHP should know that Strict Error is PHP's coding standardization warning, which is generally an error reported by PHP in order to maintain forward compatibility. That said, static calling of non-static functions is allowed in a version before php5.3, but it is not recommended in later versions! !
Okay, if you comment out Strict Error in error_reporting now, the return result will become newClass!!
In the php4 version, the subclass needs to call the method of the parent class, but the subclass has a method with the same name, so $this cannot be used, so php4 provides a method like (parentClassName::method()). (Of course php5 adds the keyword parent)
But this method provided by php4 actually allows static calling of a non-static method! ! Due to the need for forward compatibility in the background, this feature has become a feature that cannot be deleted (it must be ensured that the code of the previous version can run in the PHP environment of the later version).
Just added Strict Error to prompt this kind of call.
Underlying implementation reasons
Okay, as for the implementation reasons why this situation occurs, this article by Brother Niao has an explanation http://www.laruence.com/2012/06/ 14/2628.html
First of all, you need to subvert your own point of view. What is a static call? It does not mean that there is:: it is a static call, but look at the calling scope.
“The object pointed to by the $this pointer is the calling scope when this method is called.”
I will change the sentence translation:
Static calls do not have calling scope. The object pointed to by $this in non-static calls $this->abc() is the calling scope.
Calling scope is passed when each sentence is called.
Understand the following code:
Back to the top example
myClass::getName();
At this time, since keywords like parent are not used and $this is not reassigned, the calling scope has not changed and is still $app. That is to say, at this time, all $this pointers that appear point to $app.
Okay, the following things are easy to understand. echo $this->name; naturally calls the name attribute of the calling scope.