Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

If I have a class name in $name, how can I create an object of type \folder\$name? Ideally I'd like to interpolate the $name so that I can create the object with just a single line of code.

The following doesn't seem to work:

$obj = new \folder\$name();
like image 750
Z55 Avatar asked Feb 05 '26 05:02

Z55


1 Answers

The problem is youre trying to use a variable as part of a FQCN. You cannot do that. The FQCN can be a variable itself like:

$fqcn = '\folder\classname';
$obj = new $fqcn();

Or you can delcare the namespace at the top of the file:

namespace folder;
$fqcn = 'classname';
$obj = new $fqcn;

Or if the file belongs to another namespace you can use the class to "localize" it:

namespace mynamespace;
use folder\classname;

$fqcn = 'classname';
$obj = new $fqcn();

A more concrete example of something i assume to be 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 in more detail here: http://php.net/manual/en/language.namespaces.dynamic.php

like image 92
prodigitalson Avatar answered Feb 06 '26 21:02

prodigitalson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!