Search code examples
phpclassstaticclass-method

Call static function from variable


I have the following setup:

class test {
     public static function something() {
          $somethingElseFunction = "somethingElse";

          // How can I call the method with the name saved in variable?
     }

     public static function somethingElse($a) {
          echo 'bla';
     }
}

How can I call the function using the variable? (the function name is in variable). Also I need to do a function_exists() for it.

Tried this:

    if (function_exists(self::$somethingElseFunction ())) {
                if (!call_user_func(self::$somethingElseFunction , $a)) {

                }
            }

Didn't work.


Solution

  • In PHP>=5.4 you can use just self:: de-reference:

    self::$somethingElseFunction();
    

    -but in earlier versions that will cause error (because it wasn't allowed to use dynamic static methods de-reference). So then you can always use such things as call_user_func_array() :

    class test {
         public static function something() {
              $somethingElseFunction = "somethingElse";
    
             call_user_func_array(array(__CLASS__, $somethingElseFunction), array("bla"));
         }
    
         public static function somethingElse($a) {
              var_dump($a);
         }
    }
    
    test::something();
    

    -this will work for PHP>=5.0

    About function_exists() call - it expects string as parameter, thus I recommend to use method_exists() - because that function is intended to do the stuff:

     public static function something() {
         $somethingElseFunction = "somethingElse";
         if(method_exists(__CLASS__, $somethingElseFunction))
         {
            call_user_func_array(array(__CLASS__, $somethingElseFunction), array("bla"));
         }
     }