Understanding Non-Static Method Invocation with Double Colon (::)
When attempting to call a non-static method using the syntax of static methods (class::method), you may encounter an error. Contrary to being a configuration issue, this behavior is intrinsic to PHP's design.
In PHP, non-static methods require an instance to be created first in order to be invoked. The error occurs because when using class::method syntax, no instance is explicitly provided.
Distinction Between Static and Non-Static Methods
Static methods can be called without an instance of the class, while non-static methods require an instance. This distinction is evident in the example below:
class Teste { public function fun1() { echo 'fun1'; } public static function fun2() { echo "static fun2" ; } } Teste::fun2(); // This is valid because fun2 is a static method Teste::fun1(); // This will generate an error because fun1 is not a static method
Inconsistent Behavior
However, PHP exhibits some inconsistent behavior with non-static methods called statically. If a non-static method is called statically from within a non-static method of the same class, $this within the non-static method will refer to the current instance of the class.
class A { public function test() { echo $this->name; } } class C { public function q() { $this->name = 'hello'; A::test(); } } $c = new C; $c->q(); // This will print 'hello'
This behavior can be considered erroneous with strict error reporting enabled.
Conclusion
Calling non-static methods using the syntax of static methods is generally discouraged. It can lead to unexpected behavior or errors. Instead, it's recommended to use the proper syntax for invoking non-static methods, which involves creating an instance of the class and then calling the method on that instance.
The above is the detailed content of Why Can\'t I Call Non-Static PHP Methods Using the Double Colon (::) Operator?. For more information, please follow other related articles on the PHP Chinese website!