Php 使用变量名实例化类
我正在尝试这样做:Php 使用变量名实例化类,php,oop,class,controllers,Php,Oop,Class,Controllers,我正在尝试这样做: $controller=新的$controller'控制器' 如果$controller是Pages,则将创建PagesController类的新实例。但是,我得到了这个错误: Fatal error: Class 'Pages' not found in C:\xampp\htdocs\test\application\app.php on line 25 该类名为PagesController 我以前在PHP中见过这种方法,但是我找不到任何关于它的文档。这样做吧 $co
$controller=新的$controller'控制器'代码>
如果$controller
是Pages
,则将创建PagesController
类的新实例。但是,我得到了这个错误:
Fatal error: Class 'Pages' not found in C:\xampp\htdocs\test\application\app.php on line 25
该类名为PagesController
我以前在PHP中见过这种方法,但是我找不到任何关于它的文档。这样做吧
$controller = $controller . 'Controller';
$controller = new $controller();
这样做
$controller = $controller . 'Controller';
$controller = new $controller();
尝试:
文档:
试试:
文档:
只有在指定完整名称空间时,上述答案才有效,无论您之前是使用use
还是namespace
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
只有在指定完整名称空间时,上述答案才有效,无论您以前是使用use
还是namespace
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
第一个方法导致语法错误,但第二个方法产生此错误可捕获致命错误:无法将PagesController类的对象转换为字符串。此错误是否发生在编写$controller=new$controller的行上代码>?抱歉,这是另一行,用于检查我在die()
'ing$controller
处的错误。这个解决方案毕竟是有效的,尽管克里斯在你之前几分钟发布了它,所以我会接受他的回答。非常感谢。第一个方法导致语法错误,但第二个方法产生此错误可捕获致命错误:无法将PagesController类的对象转换为字符串。此错误是否发生在编写$controller=new$controller的行上代码>?抱歉,这是另一行,用于检查我在die()
'ing$controller
处的错误。这个解决方案毕竟是有效的,尽管克里斯在你之前几分钟发布了它,所以我会接受他的回答。非常感谢。与上面相同的错误:可捕获致命错误:无法将PagesController类的对象转换为字符串
这是正确的方法。它在哪一行显示错误?您是否在构造函数中执行任何操作?与上面相同的错误:可捕获致命错误:无法将PagesController类的对象转换为字符串
这是正确的方法。它在哪一行显示错误?你在构造器中做什么?