Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic loading of classes can't address namespace/use

Tags:

namespaces

php

I have noticed that when I am using namespacing that loading classes dynamically doesn't work the same as when I'm loading them statically. So, for instance, without the use of namespaces the following are equivalent in their action of instantiating a class called FooBar:

$foobar = new FooBar();

and

$classname = "FooBar";
$foobar = new $classname;

However if when using namespacing I have some code like this:

<?php

namespace Structure\Library;

$foobar = new UserService();
$classname = "UserService";
$barfoo = new $classname;

In this case the UserService class's fully qualified name is Structure\Library\UserService and if I use the fully qualified name it works in both cases but if I use just the shortcut name of 'UserService' it only works when instantiated with the static method. Is there a way to get it to work for both?

P.S. I am using an autoloader for all classes ... but I'm assuming that the problem is happening before the autoloader and is effecting the class string that is passed to the autoloader.

like image 255
ken Avatar asked Mar 22 '13 18:03

ken


1 Answers

I think this is a case of reading the documentation. See example 3:

http://php.net/manual/en/language.namespaces.importing.php

Seems to confirm my earlier comment.

<?php
    namespace foo\bar;

    $classStr = "myClass";    
    $nsClass = "\\foo\\bar\\myClass";

    $x = new myClass;    // instantiates foo\bar\myClass, because of declared namespace at top of file
    $y = new $classStr;  // instantiates \myClass, ignoring declared namespace at top of file
    $z = new $nsClass    // instantiates foo\bar\myClass, because it's an absolute reference!
?>
like image 107
cartbeforehorse Avatar answered Sep 20 '22 14:09

cartbeforehorse