7

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) {
    }
  }
}
chriso
  • 2,552
  • 1
  • 20
  • 16
  • why would you need to know that anyways? – Gordon Mar 30 '11 at 09:08
  • Both calls _are_ static calls. It's a static function. The function itself should have no concept of a non-static context. Why do you think you need to know this? – Lightness Races in Orbit Mar 30 '11 at 09:11
  • just curious - I was exploring the concept of (pseudo?) overloading in PHP => `Class::method($instance1, $instance2, $param)` vs. `$instance1->method($instance2, $param)` (w/ same method name) – chriso Mar 30 '11 at 09:16
  • if it takes two params in one call and three in another, chances are the method does different things depending on those. Methods should do only one thing, so you should have two methods for that. If it's just for getting variable number of arguments, use `func_get_args` – Gordon Mar 30 '11 at 09:26
  • Possible duplicate of [How do I check in PHP that I'm in a static context (or not)?](http://stackoverflow.com/questions/1858538/how-do-i-check-in-php-that-im-in-a-static-context-or-not) – kmoser Dec 07 '16 at 05:49

1 Answers1

3

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.

mario
  • 144,265
  • 20
  • 237
  • 291