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.
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!
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With