"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Posted on 2025-03-22
Browse:196

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:

class Action {
    function n() {/* some implementation */}
}

class MyAction extends Action {/* further implementation */}

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:

class Action {
    public static function n() {
        return get_called_class();
    }
}

class MyAction extends Action {

}

echo MyAction::n(); // Output: MyAction

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:

class Action {
    public function n(){
        return get_class($this);
    }
}

class MyAction extends Action {

}

$foo = new MyAction;

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

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3