PHP static function being called in dynamic environment

こ雲淡風輕ζ 提交于 2020-01-05 16:33:33

问题


Since when PHP allows to call static function like a dynamic function?

I am using php 5.3.2

class weird{

    public static function iamstatic($calledFrom){
            echo "I am  a static function called with  a $calledFrom operator\n";
    }

    public function test(){
            self::iamstatic("static");
            $this->iamstatic("dynamic");
    }

 }

$c = new weird();
$c->test();

weird::iamstatic("Static outside class");
$c->iamstatic("Dynamic outside class");

This outputs :

I am  a static function called with  a static operator
I am  a static function called with  a dynamic operator
I am  a static function called with  a Static outside class operator
I am  a static function called with  a Dynamic outside class operator

回答1:


It was always possible for php5.0 and above.

http://3v4l.org/14PYp#v500

Also, it's mentioned in documentation (static)

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).

And this not a bug (static methods assigned to instances)




回答2:


I wasn't aware this was possible, although it probably doesn't matter. Your static method won't let you reference $this, so you won't get very far using it in a non static context. If you don't need to refer to $this, then it won't matter either way, which is what your code is proving.



来源:https://stackoverflow.com/questions/24795599/php-static-function-being-called-in-dynamic-environment

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