Home > Article > Backend Development > How to Get the Class Name from an Extended PHP Class in a Static Method Call?
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:
<code class="php">class Action { public static function n() { return get_called_class(); } } class MyAction extends Action { } echo MyAction::n(); // Outputs "MyAction"</code>
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:
<code class="php">class Action { public function n() { echo get_class($this); } } class MyAction extends Action { } $foo = new MyAction; $foo->n(); // Outputs "MyAction"</code>
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.
The above is the detailed content of How to Get the Class Name from an Extended PHP Class in a Static Method Call?. For more information, please follow other related articles on the PHP Chinese website!