使用变量名来实例化一个类

时间:2012-09-08 17:00:19

标签: php oop class controllers

我正在尝试做这样的事情:

$controller = new $controller . 'Controller';

如果PagesController$controller,那么会创建Pages类的新实例。但是我收到了这个错误:

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

该类名为PagesController

我以前在PHP中看到过这个,但我找不到任何文档。

3 个答案:

答案 0 :(得分:4)

这样做

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

答案 1 :(得分:0)

尝试:

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

文档:
Constructors and Destructors
Variable variables

答案 2 :(得分:0)

上述答案仅在您指定完整命名空间时有效,无论您之前是否使用过usenamespace

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
相关问题