Is there any way I can check if a method is being called statically or on an instantiated object?
When to define static methods ? The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method.
To simplify the reasoning, think of static methods as glorified global functions. You cannot use $this inside of a global function for the same reasons, $this refers to a class instance and the function does not contain an instance of anything, without passing it in as a parameter, same as static methods.
Try the following:
class Foo { function bar() { $static = !(isset($this) && $this instanceof self); } }
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'] == '::'; } }
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