Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: get_called_class() vs get_class($this)

Tags:

In PHP what is the difference between get_called_class() and get_class($this) when used inside an instance?

Example:

class A {     function dump() {         echo get_called_class();         echo get_class($this);     } }  class B extends A {}  $A = new A(); $B = new B();  $A->dump(); // output is 'AA' $B->dump(); // output is 'BB' 

Is there any difference in this case?

When should I be using one or the other get_called_class() or get_class($this)?

like image 955
sebataz Avatar asked May 13 '13 05:05

sebataz


2 Answers

In this case there's no difference, because $this always points to the correct instance from which the class name is resolved using get_class().

The function get_called_class() is intended for static methods. When static methods are overridden, this function will return the class name that provides the context for the current method that's being called.

like image 74
Ja͢ck Avatar answered Oct 07 '22 00:10

Ja͢ck


For much faster alternative of get_called_class() in PHP >= 5.5, use static::class. It works to get the top level class for static method calls, as well as for inherited methods.

like image 26
Michael Zabka Avatar answered Oct 07 '22 00:10

Michael Zabka