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

时间:2022-09-10 23:10:32

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上是不同的,但在后来的版本中并非如此。有没有解决这个问题?

2 个解决方案

#1


63  

$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.

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

#2


4  

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"

#1


63  

$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.

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

#2


4  

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"