Search code examples
phpnamespacesautoload

Instantiating class by string using PHP 5.3 namespaces


I can't get around an issue instantiating a new class by using a string variable and PHP 5.3. namespaces. For example, this works;

$class = 'Reflection';
$object = new $class();

However, this does not;

$class = '\Application\Log\MyClass';
$object = new $class();

A fatal error gets thrown stating the class cannot be found. However it obviously can be instantiated if using the FQN i.e.;

$object = new \Application\Log\MyClass;

I've found this to be aparrent on PHP 5.3.2-1 but not not in later versions. Is there a work around for this?


Solution

  • $class = 'Application\Log\MyClass';
    $object = new $class();
    

    The starting \ introduces a (fully qualified) namespaced identifier, but it's not part of the class name itself.