Home  >  Article  >  Backend Development  >  How to Get the Classname of an Extended Class from a Static Method Call in PHP?

How to Get the Classname of an Extended Class from a Static Method Call in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 21:29:29936browse

How to Get the Classname of an Extended Class from a Static Method Call in PHP?

Retrieving the Classname from a Static Call in an Extended PHP Class

Extending classes in PHP allows for the creation of subclasses that inherit the properties and methods of their parent class. However, static methods in the parent class cannot directly access the classname of the extended class.

Problem:

Get the classname of the extended class when calling a static method from that class.

For Example:

<code class="php">class Action {
    function n() {/* something */}
}

class MyAction extends Action {/* some methods here */}</code>

Calling MyAction::n() should return "MyAction". However, __CLASS__ in the Action class returns only "Action".

Late Static Bindings (PHP 5.3 ):

Since PHP 5.3, late static bindings enable resolving the target class for static method calls at runtime. Use get_called_class() to retrieve the classname:

<code class="php">class Action {
    public static function n() {
        return get_called_class();
    }
}

class MyAction extends Action {

}

echo MyAction::n(); //displays MyAction</code>

Alternatively:

If the static method is not static, use get_class($this) in the method to obtain the classname.

The above is the detailed content of How to Get the Classname of an Extended Class from a Static Method Call in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn