How can I name a fully qualified type using a variable?

If I have a class name in $name

, how can I create an object of the type \folder\$name

? Ideally, I would like to interpolate $name

so that I can create an object with just one line of code.

The following doesn't work:

$obj = new \folder\$name();

      

+3


source to share


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


Must not be

new \folder\$arr[0];

      

but not

new \folder\$arr[0]();

      



Also, I am not very familiar with PHP and I have never seen this syntax before. I suggest:

namespace \folder;
$obj = new $arr[0];

      

I'm not sure if you can do this with just one line and no namespaces.

+1


source







All Articles