如果我在$name
中有一个类名,如何创建一个类型为 'folder'$name
的对象?理想情况下,我想插入$name
,以便只需一行代码即可创建对象。
以下方法似乎不起作用:
$obj = new 'folder'$name();
问题是您尝试将变量用作 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
不应该是
new 'folder'$arr[0];
而不是
new 'folder'$arr[0]();
另外,我对PHP不太熟悉,以前也从未见过这种语法。我的建议是:
namespace 'folder;
$obj = new $arr[0];
我不确定您是否可以用一行并且没有命名空间来做到这一点。