-1

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();
        }
    }
}
Umair Shah
  • 2,305
  • 2
  • 25
  • 50
Evgeny Musonov
  • 181
  • 3
  • 9

2 Answers2

-1

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');
Maksym Fedorov
  • 6,383
  • 2
  • 11
  • 31
-1

You can put the class name in a variable and call it with the method, or put the class name and method into a variable and then call it. It is also possible to use call_user_func ().

class Myclass{
  public static function myMethod(){
    return "return from Myclass::myMethod";
  }
}

//only class name in a variable
$curClass = 'Myclass';
echo $curClass::myMethod();

//class and Method in a variable
$classAndmethod = 'Myclass::myMethod';
echo $classAndmethod();

tested with php 7.2.21.

jspit
  • 7,276
  • 1
  • 9
  • 17