Determine if the static method was called statically or as an instance method

In PHP, static methods can be called as if they were instance methods:

class A { public static function b() { echo "foo"; } } $a = new A; A::b(); //foo $a->b(); //foo 

Is there a way to determine inside b() whether the method was called statically or not?

I tried isset($this) , but in both cases it returns false, and debug_backtrace() shows that both calls are actually static calls

 array(1) { [0]=> array(6) { ["file"]=> string(57) "test.php" ["line"]=> int(23) ["function"]=> string(1) "b" ["class"]=> string(1) "A" ["type"]=> string(2) "::" ["args"]=> array(0) { } } } Foo array(1) { [0]=> array(6) { ["file"]=> string(57) "test.php" ["line"]=> int(24) ["function"]=> string(1) "b" ["class"]=> string(1) "A" ["type"]=> string(2) "::" ["args"]=> array(0) { } } } 
+7
source share
1 answer

The isset trick only works if you don't declare the method explicitly as static . (Because this is what turns the call of the object β†’ into a static call.)

Methods can still be called via class::method() if you are not using a static modifier.

+3
source

All Articles