How do I check in PHP that I'm in a static context (or not)?
Try the following:
class Foo {
function bar() {
$static = !(isset($this) && get_class($this) == __CLASS__);
}
}
Source: seancoates.com via Google
"Digging it out of debug_backtrace()" isn't too much work. debug_backtrace() had a 'type' member that is '::' if a call is static, and '->' if it is not. So:
class MyClass {
public function doStuff() {
if (self::_isStatic()) {
// Do it in static context
} else {
// Do it in object context
}
}
// This method needs to be declared static because it may be called
// in static context.
private static function _isStatic() {
$backtrace = debug_backtrace();
// The 0th call is to _isStatic(), so we need to check the next
// call down the stack.
return $backtrace[1]['type'] == '::';
}
}
Checking if $this
is set won't work always.
If you call a static method from within an object, then $this
will be set as the callers context. If you really want the information, I think you'll have to dig it out of debug_backtrace
. But why would you need that in the first place? Chances are you could change the structure of your code in a way so that you don't.