Skip to content
Advertisement

Use a variabel as a class name in php or Cakephp 3

I am trying to run a array of command from another command. somthing similar to cronjob but with a view edit add option by end user. this is working :

                $fooCommand = new AppCommandfooCommand();
                $barCommand = new AppCommandbarCommand();

but what i need is :

            $classes = [
                "foo",
                "bar"
            ];
            foreach ($classes as $class) {
                $otherCommand = new '\App\Command\' .$class. Command();
                # code...
            }

something similar to that. iterate in an array and initiate the class. practically running the commands from the database.

Advertisement

Answer

You need to separate your classname and use variables variable

foreach ($classes as $class) {
    $_class = "\App\Command\{$class}Command";
    $class_name = $class . 'Command';
    $$class_name = new $_class;
    # code...
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement