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

53 Views Asked by At

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

There are 2 best solutions below

1
Jerson On BEST 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...
}
1
Claudio On

You can do it like this:

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

PHP Sandbox