Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check in PHP that I'm in a static context (or not)?

Is there any way I can check if a method is being called statically or on an instantiated object?

like image 417
Jamie Rumbelow Avatar asked Dec 07 '09 08:12

Jamie Rumbelow


People also ask

When should I use static methods in PHP?

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.

Can we use this keyword in static method PHP?

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.


2 Answers

Try the following:

class Foo {    function bar() {       $static = !(isset($this) && $this instanceof self);    } } 

Source: seancoates.com via Google

like image 68
BenTheDesigner Avatar answered Sep 30 '22 09:09

BenTheDesigner


"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'] == '::';     } }  
like image 37
Chris Hoffman Avatar answered Sep 30 '22 10:09

Chris Hoffman