Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

static

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) {
    }
  }
}
like image 243
chriso Avatar asked Mar 30 '11 08:03

chriso


1 Answers

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.

like image 81
mario Avatar answered Nov 18 '22 16:11

mario