Home > Article > Backend Development > Can I retrieve the correct class name from a static method call in an extended PHP class?
Retrieving Class Name from Static Calls in Extended PHP Classes
Problem:
A PHP class hierarchy exists, with a base class Action and an extended class MyAction. A static method n() in the Action class returns its class name. However, when the method is called from the extended class MyAction, it returns "Action."
Question:
Is it possible to retrieve the correct class name from a static call in the extended class?
Answer:
Option 1: Non-Static Method
If the method is modified to be non-static and instead use the $this keyword, the get_class($this) function can be employed to obtain the class name of the extended class.
Option 2: Late Static Bindings (PHP 5.3 )
Late static bindings introduce the get_called_class() function, which resolves the runtime target class for static method calls. This allows for the retrieval of the class name directly within the method.
The above is the detailed content of Can I retrieve the correct class name from a static method call in an extended PHP class?. For more information, please follow other related articles on the PHP Chinese website!