为什么PHP new 可变class时提示错误?

度月飞天 2015-05-14 05:07:51
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();


...全文
340 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuzuning 2015-05-15
  • 打赏
  • 举报
回复
这不就对了吗? DemoController 在 Demo\Controller 命名空间下 你 $c_name="Controller\DemoController"; 也是可以的 另外请注意: use Demo\Controller\DemoController; 是使用 Demo\Controller\DemoController 命名空间 而你实际并不存在这个命名空间,因为 DemoController 是类 你若写作 use Demo\Controller\DemoController as DemoController; 就可以 $c_name="DemoController"; 了
度月飞天 2015-05-15
  • 打赏
  • 举报
回复
引用 4 楼 zy205817 的回复:
namespace Demo; use Demo\Controller\DemoController; 确定下路径是否正确
路径是对的,我若把代码
$c_name="DemoController";
换成
$c_name="Demo\Controller\DemoController";
又可以,这是什么情况?不理解
码无边 2015-05-15
  • 打赏
  • 举报
回复
namespace Demo; use Demo\Controller\DemoController; 确定下路径是否正确
度月飞天 2015-05-15
  • 打赏
  • 举报
回复
求高手指点
度月飞天 2015-05-14
  • 打赏
  • 举报
回复
引用 1 楼 xuzuning 的回复:
命名空间不对!
该怎么修改呢?赐教
xuzuning 2015-05-14
  • 打赏
  • 举报
回复
命名空间不对!

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧