gpt4 book ai didi

php - 在 PHP 中使用命名空间和自动加载从变量创建对象

转载 作者:IT王子 更新时间:2023-10-29 00:13:20 25 4
gpt4 key购买 nike

之后用我自己的评论进行编辑

I think the problem is that when PHP is parsing the file to "compile", first it translates class names to their fully qualified name. So Index will be translated to Controller\Home\Index. After that, is when PHP translates variables into their value. So if I use a variable as a class name, it won't qualified its name, because that step has already happened. And thats why is not finding the class. That's just a guess, but most likely it is that way Blockquote

结束编辑

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

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

$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

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

谢谢!


<子>额外的长尾搜索:

  • 来自变量的 php 完全限定名
  • php 从变量中的别名实例化类

最佳答案

有趣的问题。看样子,也没什么办法了。 php docs似乎明确说明了这一点:

One must use the fully qualified name (class name with namespace prefix).

在您的情况下,一个可能的解决方法是在配置中为您的 Controller 定义一个基本命名空间,并通过它们的相对命名空间注册 Controller 。

假设基本命名空间是 MyApp\Controller\ 并且我们将我们的 Controller 保存在一个数组中(为了简洁起见):

$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();

关于php - 在 PHP 中使用命名空间和自动加载从变量创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7947544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com