chriso
chriso

Reputation: 2552

Determine whether a static method has been called statically or as an instance method

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) {
    }
  }
}

Upvotes: 7

Views: 2776

Answers (1)

mario
mario

Reputation: 145482

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.

Upvotes: 3

Related Questions