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

Mary-Kate Olsen
Release: 2024-10-30 21:53:30
Original
887 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template