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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With