Call a non-static method using the region resolution operator

I found some strange (for me) behavior of the PHP interpreter, and I'm not sure how safe it is to use it in production or not.

When we call Foo::bar() , and the Foo class does not have a static bar method, but has a non-static bar method, the interpreter will call non-static bar on null (yes, that sounds ridiculous). I expected __callStatic be called in this case. But this is not what happens for some reason.

Then I found a convenient use for this behavior: to provide the class to static and non-stationary methods with the same name as this:

 class Foo { public function bar(){ if (isset($this)) { $this->nonStaticBar(); } else { static::staticBar(); } } private function nonStaticBar() { echo "Non-static\n"; } private static function staticBar() { echo "Static\n"; } } (new Foo())->bar(); // Output: "Non-static" Foo::bar(); // Output: "Static" 

Yes, I know that this approach is not elegant and architecturally wrong. The question is whether it is safe (standard compatible) to use this "function" or not. Are there other cases where isset($this) can be false ?

+6
source share
1 answer

While your example above works, this is not best practice. This is described in the PHP documentation here and it says that in versions of PHP prior to version 7, if E_STRICT report is enabled, then it gives an error:

 Strict Standards: Non-static method Foo::bar() should not be called statically in /Path/to/file.php on line 22 

Additionally, in PHP version 7 and above, invoking static functions is statically outdated and will result in the following execution error:

 Deprecated: Non-static method Foo::bar() should not be called statically in /Path/to/file.php on line 22 
+3
source

All Articles