OOP calling static method of unknown class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rythmic
    New Member
    • Feb 2010
    • 29

    OOP calling static method of unknown class

    Hi!

    PHP is really nifty in the way you can instantiate classes by using string variables like so:

    Code:
    $str_class_name = 'User';
    $instance = new $str_class_name();
    That way you can create flows where classes that are used in the same way can use the same code even if you don't know which class will use the code beforehand.

    My question is whether there is a way to do this for static methods of a class.

    so something like:
    Code:
    class User {
        public static function get_all(){
            return "calling get_all from user";
        }
    }
    
    $class_name = 'User';
    $class_name::get_all();
    The above example would of course get all users but it does not work for obvious reasons. Does anyone know a way to accomplish what I'm asking?

    best regards
    Rythmic
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    #2
    The above code does work for PHP 5.3 and newer. For older versions, you'll have to use something like: call_user_func( array('class', 'func') );

    Mark.

    Comment

    Working...