Obtaining Class Name from Extended PHP Class Static Call
In object-oriented programming, classes often extend base classes to inherit and extend their functionality. A common scenario involves the need to obtain the class name from a static method call in an extended class, despite the fact that CLASS always returns the name of the defining class.
Problem: Inaccessibility of Class Name in Parent Static Methods
Consider a scenario with two classes, Action and MyAction, where MyAction extends Action. Action defines a static method, n(), which is inaccessible via the CLASS constant within parent static methods, resulting in the CLASS value being set to "Action" regardless of the calling class.
Solutions:
1. Late Static Bindings (PHP 5.3 ):
Late static bindings allow you to determine the target class of a static method call at runtime rather than when the method is defined. This is achieved using the get_called_class() function, which returns the name of the class in which the static method was called.
For instance:
class Action {
public static function n() {
return get_called_class();
}
}
class MyAction extends Action {
}
echo MyAction::n(); // Outputs "MyAction"
2. Using get_class($this) (Non-Static Methods Only):
If the method in question is not static, you can use get_class($this) to obtain the class name from which the method was called.
For example:
class Action {
public function n() {
echo get_class($this);
}
}
class MyAction extends Action {
}
$foo = new MyAction;
$foo->n(); // Outputs "MyAction"
Conclusion:
Both late static bindings and get_class($this) offer solutions to retrieve the class name from a static method call in an extended class. Late static bindings are preferable for static methods, while get_class($this) is useful for non-static methods.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3