Search code examples
phpoopvariablesstatic-classes

How can i get access to static method through variable?


Trying to get

$class = 'MyClass';
$class::classname() - MyClass not found

So, is it possible? Or are there other options?

public function actionMultiUpdate($module)
{
    if (isset($_REQUEST['multiedit']) && count($_REQUEST['multiedit'])) {
        foreach ($_REQUEST['multiedit'] as $id => $data) {
            $model = $module::findOne($id);
            $model->weight = $data['weight'];
            $model->save();
        }
    }
}

Solution

  • You can use call_user_func to run a static method with the string class name. For example:

    class Myclass
    {
    
        public static function classname() {
            return __CLASS__;
        }
    }
    
    $class = 'MyClass';
    echo call_user_func([$class, 'classname']);
    

    Also if you want to pass variables into a static method you should pass them in the second parameter. For example:

    class MyClass
    {
        public static function doSomething($value1, $value2)
        {
            return $value1 . ' and ' . $value2;
        }
    }
    
    $class = 'MyClass';
    echo call_user_func([$class, 'doSomething'], 'first value', 'second value');