命名空间实例化通过变量

namespace user;
use robot;

$namespace = 'r\someClass';
$class = new $namespace();  // does not work

$namespace = 'obot\someClass';
$class = new $namespace();  // does work

Why doesn't this work as expected?

The reason I am using a variable is b/c "someClass" isn't known ahead of time.

So the code looks like this:

if ( $class == 'someClass' )
{
   $namespace = 'r\someClass';
}
elseif ( $class == 'someOtherClass' )
{
   $namespace = 'r\someOtherClass';
}

$class = new $namespace();

This is easy to work around, but I don't understand why:

$class = new r\someClass() will work and $class = new $namespace() will not work.

Updated:

When you use dynamic class name, you have to include the namespace name.

So the below will work:

namespace user;
use robot; // use is not necessary when you use dynamic class name.

$namespace = 'robot\someClass'; // for a dynamic class name, namespace is required.
$class = new $namespace();

Note the leading slash is not necessary, because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name.

Check the document here.

Should be able to use @xdazz answer, but you can also alias the namespace. The reason it is failing is you have to full quality namespace path.

use robot as r;

$classname = 'r\someClass';

without the

 as r

part you have to fully qualify the path later.

I stumbled upon the same issue a few minutes ago - should've looked in here ealier :) unfortunately i can't comment yet so here's a tiny hint that you can also use the __NAMESPACE__ constant instead of retyping the whole qualified namespace when your class is relative to the current namespace...

In my case i have a small factory method:

public function getService($name)
{
  $className = __NAMESPACE__ . '\Service\\' . $name;
  return new $className();
}