首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用PHP中的Namespaces和Autoload从变量创建对象

使用PHP中的Namespaces和Autoload从变量创建对象
EN

Stack Overflow用户
提问于 2018-05-23 07:16:55
回答 2查看 0关注 0票数 0

我使用Symfony2项目中的UniversalClassLoader来自动加载我的类,但是我发现了一些我无法解决的奇怪错误。

自动加载的东西工作正常,但后来我遇到了这个问题:

代码语言:javascript
复制
$controller      = new Index(); // It works!

$controller_name = "Controller\\Home\\Index";
$controller2     = new $controller_name(); // It works!

$controller_name = "Index";
$controller3     = new $controller_name(); // Fatal error: Class 'Index' not found

前两个案例工作得很好。在第一个中,由于Im使用“使用Controller \ Home” 在我的脚本开始时,我只能使用“new Index();” 没有什么问题。但是,如果不是编写“索引”,而是使用像$ var =“Index”这样的字符串变量,它不起作用。我不明白为什么。我需要这个脚本是动态的,这就是为什么我需要一个变量。

EN

回答 2

Stack Overflow用户

发布于 2018-05-23 16:01:31

代码语言:javascript
复制
$controllers = array(
    'foo/bar' => 'MyFooController',
    'baz'     => 'Foo\\MyBarController'
);

// One way how the controllers could be instantiated:

// returns 'MyApp\\Controller\\'
$namespace = $cfg->get('namespaces.controller');

$controller = $namespace.$controllers['baz'];
$controller = new $controller();
票数 0
EN

Stack Overflow用户

发布于 2018-05-23 16:21:14

代码语言:javascript
复制
// This may be working because Symfony's autoloader has found a class named Index
$controller      = new Index(); 

// A name-space call so PHP knows where to actually find the file
// Chances are the class name here is Controller_Home_Index
$controller_name = "Controller\\Home\\Index";
$controller2     = new $controller_name();

// Symfony's autloader should have picked this up, but didn't
// It's possible that with this construct Symfony cannot find the class and b/c
// it's not namespaced, PHP has no choice but to fail
$controller_name = "Index";
$controller3     = new $controller_name();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100008556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档