PHP: call to an instance method via ClassName::method syntax, results in a static call?

随声附和 提交于 2019-12-04 02:01:57

问题


Her is my code:

class MyClass 
{
   public $prop;
   public function method ()
   {
     echo $this->prop;
   }
}

Then somewhere in the code, accidently:

MyClass::method();

I would expect to have an interpretation error about the above line, because the called method is not static. Instead, the method was called, and I received an exception about $prop not existing. So i understand that the method was called as a static method, even though it's not.

Does it work this way? (Why the hell? )


回答1:


Calling non-static methods statically generates an E_STRICT level warning.

http://php.net/manual/en/language.oop5.static.php

I suppose you have E_STRICT warnings suppressed. It works (likely for legacy reasons), but it's not recommended.




回答2:


For legacy reasons, any class method could be called statically even if it wasn't declared static, because you previously couldn't declare them as such. In those cases, $this would simply refer to nothing because it's not an object-context variable.

In PHP 5 you get an E_STRICT warning for calling non-static methods statically (as you just did).



来源:https://stackoverflow.com/questions/4664511/php-call-to-an-instance-method-via-classnamemethod-syntax-results-in-a-stati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!