0

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.

James Dawson
  • 5,309
  • 20
  • 72
  • 126

3 Answers3

4

Do this

$controller = $controller . 'Controller';
$controller = new $controller();
Kris
  • 6,094
  • 2
  • 31
  • 46
  • Same error as above: `Catchable fatal error: Object of class PagesController could not be converted to string` – James Dawson Sep 08 '12 at 17:06
  • This is the proper way on how to do it. What line is it giving the error on? Are you doing anything in your constructor? – Kris Sep 08 '12 at 17:10
0

Try:

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

Documentation:
Constructors and Destructors
Variable variables

Jocelyn
  • 11,209
  • 10
  • 43
  • 60
  • The first method results in a syntax error but the second method produces this error `Catchable fatal error: Object of class PagesController could not be converted to string`. – James Dawson Sep 08 '12 at 17:05
  • Does this error happen on the line where you wrote `$controller = new $controller;`? – Jocelyn Sep 08 '12 at 17:08
  • Sorry, it was a different line to check for errors where I was `die()`'ing `$controller`. This solution works after all, although Kris posted it a few minutes before you so I'll accept his answer. Thank you! – James Dawson Sep 08 '12 at 17:09
0

The above answers will only work if you specify the full namespace regardless whether you used use or namespace before.

use \App\Article\Health as Health;

$article = new Health; // works fine

$classname = "Health";
$article = new $classname(); // Class 'Health' not found.

$c = "\\App\\Article\\$classname";
$article = new $c(); // works fine
Rápli András
  • 3,869
  • 1
  • 35
  • 55