0

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 \App\Command\fooCommand();
                $barCommand = new \App\Command\barCommand();

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.

2 Answers2

0

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...
}
Jerson
  • 1,700
  • 2
  • 10
  • 14
  • i did it like this but yours is working to:$class = '\\App\\Command\\' . $action . 'Command'; $command = new $class(); – user2735306 Nov 03 '20 at 10:21
0

You can do it like this:

foreach ($classes as $class) {
    $classWithNamespace = "\\App\\Command\\{$class}Command";
    $otherCommand = new $classWithNamespace();
}

PHP Sandbox

Claudio
  • 5,078
  • 1
  • 22
  • 33