PHP namespace with Dynamic class name

Well, just spell out the namespace in the string:

$definition = Definer::defineProfile($_SESSION['user']->UserType);
$class="\\Editor\\" . $definition;
$foo = new $class();

And if it’s a child namespace (as indicated in the comments), simply prepend the namespace with __NAMESPACE__:

$class = __NAMESPACE__ . '\\Editor\\' . $definition;

So if the current namespace is \Foo\Bar, and $definition is “Baz”, the resulting class would be \Foo\Bar\Editor\Baz

Leave a Comment