In PHP, static methods can be invoked using the class name followed by the scope resolution operator (::). However, it's generally not possible to call non-static methods in the same manner.
Non-Static Methods with Double-Colon Syntax
The code snippet below attempts to call a non-static method, fun1, using the double-colon syntax:
class Teste { public function fun1() { echo 'fun1'; } public static function fun2() { echo "static fun2" ; } } Teste::fun1(); // why? Teste::fun2(); // ok - is a static method
This code will result in an error, as non-static methods cannot be accessed directly through the class name.
Reason for Restriction
PHP employs loose typing for static vs. non-static methods. When a non-static method is called statically, the $this keyword inside that method will not refer to an instance of the class. This loose behavior can lead to inconsistent and potentially erroneous code.
Static Method Variants
The double-colon syntax is only permissible for calling static methods. Here's an example:
class StaticExample { public static function staticMethod() { echo "static method"; } } StaticExample::staticMethod(); // valid
Within Non-Static Methods
It's possible to call a non-static method statically from within a non-static method of the same class. In such cases, $this inside the called method will still refer to the correct object instance.
class A { public function nonStaticMethod() { echo $this->name; } } class C { public function callNonStatic() { $this->name = 'Example'; A::nonStaticMethod(); // valid } } $c = new C; $c->callNonStatic(); // prints Example
The above is the detailed content of Why Can\'t I Call Non-Static Methods Using the Double-Colon Syntax in PHP?. For more information, please follow other related articles on the PHP Chinese website!