How can I name a fully qualified type using a variable?
2 answers
The problem is when you are trying to use a variable as part of the FQCN. You cannot do this. FQCN can be the variable itself:
$fqcn = '\folder\classname';
$obj = new $fqcn();
Or you can handle the namespace at the top of the file:
namespace folder;
$fqcn = 'classname';
$obj = new $fqcn;
Or, if the file belongs to a different namespace, you can use
class "localize" it:
namespace mynamespace;
use folder\classname;
$fqcn = 'classname';
$obj = new $fqcn();
A more specific example of what I believe is similar to what you are trying to do:
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;
}
}
You can read more here: http://php.net/manual/en/language.namespaces.dynamic.php
+5
source to share