0

Can anyone explain why is the get_class function returning different values below? Specifically, what is it supposed to do when it is called in a base class and when it is called in a derived class?

abstract class bar {
    public function __construct()
    {
        var_dump(get_class($this)); //prints 'foo'
        var_dump(get_class()); // prints 'bar'
    }
}

class foo extends bar {
}

new foo;
SexyBeast
  • 7,913
  • 28
  • 108
  • 196

1 Answers1

5

It seems quite well explained in the documentation, but here it is:

get_class($instance) returns the class of the $instance instance, regardless of where you're calling it; get_class($this) does behave the same way, returning the class of $this.

get_class() returns the class where the method calling it is defined, thus it returns bar in your example, as that is where __construct() is defined (even though you're calling it through inheritance).

lanzz
  • 42,060
  • 10
  • 89
  • 98
  • You said that **'get_class()' returns the class where the method calling it is defined, thus it returns bar in your example, as that is where `__construct()` is defined (even though you're calling it through inheritance).** But if I add a `__construct` function to **foo**, like `function __construct() { parent::__construct(); }`, then? In this case, even though the `__construct` function is ultimately called in the parent class (thus it should return **bar**), that `__construct` function is itself called from within **foo**'s `__construct`. So why shouldn't it escalate to print **foo**? – SexyBeast Sep 12 '12 at 14:49
  • Because `get_class()` is called _in_ `bar::__construct()`. It does not matter where `bar::__construct()` is called from, only where the actual invocation of `get_class()` is. – lanzz Sep 12 '12 at 14:50
  • Thanks. Can you please contrast this method with the `__CLASS` way of getting the class? Both of them seem to do the same thing, although I suspect that it might not be so. – SexyBeast Sep 12 '12 at 14:53
  • There does not seem to be any difference between the two, and both seem to be documented to return or evaluate to the same result. A possible difference is that you can pass `get_class` as a callable to methods that expect a callable, where it will be called in the context of the called method, while you can't do that with the constant, but I cannot think of a scenario where that might be useful. – lanzz Sep 12 '12 at 14:58
  • What do you mean by passing `get_class` as a callable? – SexyBeast Sep 12 '12 at 15:01
  • Actually nevermind, `call_user_func('get_class')` apparently does not work. – lanzz Sep 12 '12 at 15:17