Search code examples
phpoopclasscontrollers

Using variable names to instantiate a class


I'm trying to do something like this:

$controller = new $controller . 'Controller';

Which would create a new instance of the PagesController class if $controller was Pages. I'm getting this error, however:

Fatal error: Class 'Pages' not found in C:\xampp\htdocs\test\application\app.php on line 25

The class is named PagesController.

I've seen this done in PHP before, but I can't find any documentation on it.


Solution

  • Do this

    $controller = $controller . 'Controller';
    $controller = new $controller();