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)
?
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.
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.
Not in this case... if dump was a static method and eliminate the $this
parameter then get_class would return "A" in both cases and get_called_class would return "B" when you did B::dump();
In this instance there is no difference, both return the name of the class, but the get_called _class has Late Static Binding
The answer, in this particular case, is : NO.
There is no difference.
Reference : (http://php.net/manual/en/function.get-class.php)
string get_class ([ object $object = NULL ] )
...
If object is omitted when inside a class, the name of that class is returned.