Home >Backend Development >PHP Tutorial >How to retrieve the class name from a static method call in extended PHP classes?

How to retrieve the class name from a static method call in extended PHP classes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 21:53:30932browse

How to retrieve the class name from a static method call in extended PHP classes?

Retrieving Class Name from Static Call in Extended PHP Class

In the world of PHP, it's often necessary to determine the classname from a static function call, especially when working with extended classes. Consider the following scenario:

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

class MyAction extends Action {/* further implementation */}</code>

In this situation, calling MyAction::n(); should return "MyAction" as the classname. However, the __CLASS__ variable only returns the parent class name ("Action").

Late Static Bindings (PHP 5.3 ):

PHP 5.3 introduced late static bindings, which enable resolving the target class at runtime. This feature makes it possible to determine the called class using the get_called_class() function:

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

class MyAction extends Action {

}

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

Alternative Approach (Pre-PHP 5.3):

Prior to PHP 5.3, an alternative solution relies on using a non-static method and the get_class() function:

<code class="php">class Action {
    public function n(){
        return get_class($this);
    }
}

class MyAction extends Action {

}

$foo = new MyAction;

echo $foo->n(); // Output: MyAction</code>

Remember, this approach only works for non-static methods, as the get_class() function takes an instance of the class as an argument.

The above is the detailed content of How to retrieve the class name from a static method call in extended PHP classes?. 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