Strange behavior when __callStatic () is run from a non-static method

I found this strange behavior with PHP classes (v5.3.8).

You have:

class foo { function __call($func, $args) { if ($func == 'bar') echo "non-static __call"; } static function __callStatic($func, $args) { if ($func == 'bar') echo "__callStatic"; } function callMe() { self::bar(); } } 

Then follow these steps:

 foo::bar() // outputs '__callStatic' as expected. $f = new foo; $f->callMe(); // outputs 'non-static __call', as I did not expect. 

You see, a non-existent static method called from a non-static function fires __call() instead of __callStatic() . I was wondering if this should work like that, or is this some kind of mistake?

[EDIT]

I forgot to try static::bar(); on callMe() , but no, that didn't work either.

I (I think I) understand the comment, but still ... if I call the class itself, and not an instance or object, then for me the logical logic says that it should call __callStatic (). Oh good.

Thanks for your answers / comments.

+4
source share
2 answers

You may be confused by what these things mean from the class context method:

 class B extends A { public function test() { A::foo(); self::foo(); static::foo(); } } 

There are no such means as "calling a static method named foo". It simply means β€œcall a method named foo” in a place in the inheritance tree, as indicated by what is left of the colon.

Usually, without magic, you only have one function called foo , so the meaning is simple. However, when you overload both magic methods, the call is ambiguous . PHP defaults to __call() before __callStatic() .

+3
source

Static methods, variables belong to classes not objects, so I think this should work like that.

+1
source

Source: https://habr.com/ru/post/1398653/


All Articles