PHP static function being called in dynamic enviro

2019-07-26 16:49发布

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

2条回答
何必那么认真
2楼-- · 2019-07-26 17:04

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-26 17:12

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)

查看更多
登录 后发表回答