使用 PHP 5.3 命名空间按字符串实例化类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5072352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:43:28  来源:igfitidea点击:

Instantiating class by string using PHP 5.3 namespaces

phpnamespacesautoload

提问by Kevin

I can't get around an issue instantiating a new class by using a string variable and PHP 5.3. namespaces. For example, this works;

我无法解决使用字符串变量和 PHP 5.3 实例化新类的问题。命名空间。例如,这有效;

$class = 'Reflection';
$object = new $class();

However, this does not;

然而,这不是;

$class = '\Application\Log\MyClass';
$object = new $class();

A fatal error gets thrown stating the class cannot be found. However it obviously can be instantiated if using the FQN i.e.;

抛出一个致命错误,说明找不到该类。然而,如果使用 FQN,它显然可以被实例化,即;

$object = new \Application\Log\MyClass;

I've found this to be aparrent on PHP 5.3.2-1 but not not in later versions. Is there a work around for this?

我发现这在 PHP 5.3.2-1 上很明显,但在以后的版本中则不然。有解决办法吗?

回答by Artefacto

$class = 'Application\Log\MyClass';
$object = new $class();

The starting \introduces a (fully qualified) namespaced identifier, but it's not part of the class name itself.

开头\引入了(完全限定的)命名空间标识符,但它不是类名本身的一部分。

回答by Francesco Casula

Another way to achieve the same result but with dynamic arguments is as follows. Please consider the class below as the class you want to instantiate.

实现相同结果但使用动态参数的另一种方法如下。请将下面的类视为您要实例化的类。

<?php

// test.php

namespace Acme\Bundle\MyBundle;

class Test {
    public function __construct($arg1, $arg2) {
        var_dump(
            $arg1,
            $arg2
        );
    }
}

And then:

进而:

<?php

require_once('test.php');

(new ReflectionClass('Acme\Bundle\MyBundle\Test'))->newInstanceArgs(['one', 'two']);

If you are not using a recent version of PHP, please use the following code that replaces the last line of the example above:

如果您使用的不是最新版本的 PHP,请使用以下代码替换上面示例的最后一行:

$r = new ReflectionClass('Acme\Bundle\MyBundle\Test');
$r->newInstanceArgs(array('one', 'two'));

The code will produce the following output:

该代码将产生以下输出:

string(3) "one"
string(3) "two"

回答by Przemek Kro

I had the same problem and I have found some way around this problem. Probably not very efficient, but at least works.

我遇到了同样的问题,我找到了解决这个问题的方法。可能效率不高,但至少有效。

function getController($controller)
{
    return new $controller;
}

$object = getController('Application\Log\MyClass');