2

Possible Duplicate:
How to tell whether I’m static or an object?

Let's say I have a FooClass with a bar() method. Inside of the bar() method, is there any way to tell if it's being called statically or not, so I can treat these two cases differently?

FooClass::bar();
$baz = new FooClass();
$baz->bar();
Community
  • 1
  • 1
GSto
  • 41,512
  • 37
  • 133
  • 184
  • 6
    You probably should think about a redesign of the class if you want to have a method that should be both statically and non-statically... why do you want to do this? – Felix Kling Sep 29 '10 at 17:18
  • 2
    turn on E_STRICT error reporting to make php scream at you when you do it wrong – user187291 Sep 29 '10 at 17:30

1 Answers1

7
class FooClass {

    function bar() {
        if ( isset( $this ) && get_class($this) == __CLASS__ ) {
            echo "not static";
        }
        else {
            echo "static";
        }
    }

}

FooClass::bar();
$baz = new FooClass();
$baz->bar();
Galen
  • 29,976
  • 9
  • 71
  • 89
  • Thats it, but wrap `$this` in `isset()` to not trigger any additional notice – dev-null-dweller Sep 29 '10 at 17:22
  • 1
    This only works in the global scope. If you call it from another class, $this will be set, just not the object you want. Might want to try `isset($this) && get_class($this) == __CLASS__` – landons Dec 30 '11 at 08:28
  • If FooClass is inherited by a new class, will this work? __CLASS__ provides the class name of the file it is declared in, so that would be FooClass and presumably not InheritedFooClass that extends FooClass? – Jason Jun 26 '14 at 23:51