如果我在$name
中有一个类名,我该如何创建\folder\$name
类型的对象?理想情况下,我想插入$name
,这样我就可以用一行代码创建对象。
以下似乎不起作用:
$obj = new \folder\$name();
答案 0 :(得分:5)
问题是你试图将变量用作FQCN的一部分。你不能这样做。 FQCN本身可以是变量,如:
$fqcn = '\folder\classname';
$obj = new $fqcn();
或者您可以在文件顶部删除命名空间:
namespace folder;
$fqcn = 'classname';
$obj = new $fqcn;
或者,如果文件属于另一个命名空间,您可以use
将该课程定位到"本地化"它:
namespace mynamespace;
use folder\classname;
$fqcn = 'classname';
$obj = new $fqcn();
我认为与您尝试做的事情类似的更具体的例子:
namespace App\WebCrawler;
// any local uses of the File class actually refer to
// \App\StorageFile instead of \App\WebCrawler\File
use App\Storage\File;
// if we didnt use the "as" keyword here we would have a conflict
// because the final component of our storage and cache have the same name
use App\Cache\File as FileCache;
class Client {
// the FQCN of this class is \App\WebCrawler\Client
protected $httpClient;
protected $storage;
protected $cache
static protected $clients = array(
'symfony' => '\Symfony\Component\HttpKernel\Client',
'zend' => '\Zend_Http_Client',
);
public function __construct($client = 'symfony') {
if (!isset(self::$clients[$client])) {
throw new Exception("Client \"$client\" is not registered.");
}
// this would be the FQCN referenced by the array element
$this->httpClient = new self::$clients[$client]();
// because of the use statement up top this FQCN would be
// \App\Storage\File
$this->storage = new File();
// because of the use statement this FQCN would be
// \App\Cache\File
$this->cache = new FileCache();
}
public static function registerHttpClient($name, $fqcn) {
self::$clients[$name] = $fqcn;
}
}
您可以在此处详细阅读:http://php.net/manual/en/language.namespaces.dynamic.php
答案 1 :(得分:1)
不应该是
new \folder\$arr[0];
而不是
new \folder\$arr[0]();
另外,我对PHP不太熟悉,之前我从未见过这种语法。我的建议是:
namespace \folder;
$obj = new $arr[0];
我不确定你是否可以只使用一行而不使用命名空间。