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 of determining inside of b()
whether the method was called statically or not?
I've tried isset($this)
but it returns false in both cases, and debug_backtrace()
seems to show 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) {
}
}
}
The isset
trick only works if you don't declare the method explicitly as static
. (Because that's exactly what turns the -> object invocation into a static call.)
Methods can still be called via class::method()
if you don't use the static modifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With