Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用变量名实例化类_Php_Oop_Class_Controllers - Fatal编程技术网

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类的对象转换为字符串
这是正确的方法。它在哪一行显示错误?你在构造器中做什么?