It might make it more clear if said this way:
One must note that when using a dynamic class name, function name or constant name, the "current namespace", as in http://www.php.net/manual/en/language.namespaces.basics.php is global namespace.
One situation that dynamic class names are used is in 'factory' pattern. Thus, add the desired namespace of your target class before the variable name.
namespaced.php
<?php
// namespaced.php
namespace Mypackage;
class Foo {
public function factory($name, $global = FALSE)
{
if ($global)
$class = $name;
else
$class = 'Mypackage\\' . $name;
return new $class;
}
}
class A {
function __construct()
{
echo __METHOD__ . "<br />\n";
}
}
class B {
function __construct()
{
echo __METHOD__ . "<br />\n";
}
}
?>
global.php
<?php
// global.php
class A {
function __construct()
{
echo __METHOD__;
}
}
?>
index.php
<?php
// index.php
namespace Mypackage;
include('namespaced.php');
include('global.php');
$foo = new Foo();
$a = $foo->factory('A'); // Mypackage\A::__construct
$b = $foo->factory('B'); // Mypackage\B::__construct
$a2 = $foo->factory('A',TRUE); // A::__construct
$b2 = $foo->factory('B',TRUE); // Will produce : Fatal error: Class 'B' not found in ...namespaced.php on line ...
?>