Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP namespace with Dynamic class name

Tags:

namespaces

php

Wondering if anyone else has encountered this problem when utilizing the new ability to namespace classes using PHP 5.3.

I am generating a dynamic class call utilizing a separate class for defining user types in my application. Basically the class definer takes an integer representation of types and interprets them, returning a string containing the classname to be called as the model for that user.

I have an object model for the user's type with that name defined in the global scope, but I have another object with the same name for the user's editor in the Editor namespace. For some reason, PHP won't allow me to make a namespaced dynamic call as follows.

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

The identical syntax works for calling the global basic object model in the global namespace and I use it this way reliably throughout the application.

$definition = Definer::defineProfile($_SESSION['user']->UserType);
new $definition();

This will correctly call the dynamically desired class.

Is there a reason the two would behave differently, or has dynamic calling for namespaces not been implemented in this manor yet as this is a new feature? Is there another way to dynamically call a class from another namespace without explicitly placing its name in the code, but from within a variable?

like image 205
DeaconDesperado Avatar asked Dec 22 '10 20:12

DeaconDesperado


1 Answers

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

like image 111
ircmaxell Avatar answered Sep 21 '22 16:09

ircmaxell