Calling Non-Static Methods Using Double Colon Syntax
In PHP, it's possible to call non-static methods using the syntax of static methods, class::method. However, why is it that such calls fail?
Consider the following example:
class Teste { public function fun1() { echo 'fun1'; } public static function fun2() { echo "static fun2"; } }
Calling Teste::fun2() works because it's a static method, but calling Teste::fun1() raises an error.
The explanation lies in PHP's loose handling of static vs. non-static methods. When a non-static method is called statically from within a non-static method of class C, $this inside the non-static method ns refers to the instance of C.
For example:
class A { public function test() { echo $this->name; } } class C { public function q() { $this->name = 'hello'; A::test(); } } $c = new C; $c->q(); // prints hello
Although this may cause unexpected behavior, it's not an error unless strict error reporting is enabled. Therefore, calling non-static methods statically using double colon syntax is discouraged, as it can lead to errors or confusing behavior.
The above is the detailed content of Why Do Calls to Non-Static Methods Using PHP\'s Double Colon Syntax Fail?. For more information, please follow other related articles on the PHP Chinese website!