What is the difference between __CLASS__ and get_called_class() in PHP when trying to determine the class in which a method was called?
When trying to determine the class in which a method was called in PHP, the __CLASS__ magic constant refers to the class in which it is used, while the get_called_class() function returns the name of the class in which the method was actually called. This means that if a method is inherited by a child class and called from there, get_called_class() will return the child class name, while __CLASS__ will return the parent class name.
class ParentClass {
public function getClassUsingMagicConstant() {
echo __CLASS__;
}
public function getClassUsingGetCalledClass() {
echo get_called_class();
}
}
class ChildClass extends ParentClass {
}
$parent = new ParentClass();
$child = new ChildClass();
$parent->getClassUsingMagicConstant(); // Output: ParentClass
$parent->getClassUsingGetCalledClass(); // Output: ParentClass
$child->getClassUsingMagicConstant(); // Output: ParentClass
$child->getClassUsingGetCalledClass(); // Output: ChildClass