当前位置: 代码迷 >> PHP >> 为什么PHP new 可变class时提示异常
  详细解决方案

为什么PHP new 可变class时提示异常

热度:13   发布时间:2016-04-28 17:22:15.0
为什么PHP new 可变class时提示错误?
namespace Demo;
use Demo\Controller\DemoController;

$c_str=$_GET['c'];
$c_name="DemoController";

require 'Controller/'.$c_name.'.php';

$method=$_GET['a'];

$demo=new $c_name;  // 我在这块手工填写: $demo=new DemoController; 是没问题的,换成$c_name 就报错
$demo->$method();



------解决思路----------------------
namespace Demo;
use Demo\Controller\DemoController;

确定下路径是否正确
------解决思路----------------------
这不就对了吗?
DemoController 在 Demo\Controller 命名空间下


$c_name="Controller\DemoController";
也是可以的

另外请注意:
use Demo\Controller\DemoController;
是使用 Demo\Controller\DemoController 命名空间
而你实际并不存在这个命名空间,因为 DemoController 是类
你若写作
use Demo\Controller\DemoController as DemoController;
就可以 $c_name="DemoController"; 了
  相关解决方案