问题
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