And so, there is a class:

`namespace Controllers; class IndexController { ... }` 

How in other class to use methods of this class?

 namespace Library\MainFunction; class MainFunction { public function foo() { $class = 'Controllers\\IndexController'; $obj = new $class; \\ ошибка Class 'Controllers\IndexController' not found } } 

What am I doing wrong and how is it right? The call is through a string variable, because the controller will change.

  • Are you sure that you connected the file with the IndexController class to the file with the MainFunction class? - ArchDemon
  • composer did it for me. If I call the class directly without a variable, then everything works fine. - Dmitriy
  • \\Controllers\\IndexController then you can try this. For in your example the class is searched from the current namespace - ArchDemon
  • Class '\Controllers\IndexController' not found - Dmitriy
  • one

1 answer 1

And so, I will sign in detail how to create an instance with his name in the string variable. We use OOP with a namespace. It doesn't matter if you specified use at the beginning of the script. The class must be called completely! those.

 namespace a\b\ use c\d; ... public function foo($d){ $sting = '\\c\\'.$d; $obj = new $string(); } 

It is important not to forget to specify the brackets after the line, otherwise it will not work either.

Russian answer found here