Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

PHP namespace with Dynamic class name

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?

question from:https://stackoverflow.com/questions/4513366/php-namespace-with-dynamic-class-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 FooBar, and $definition is "Baz", the resulting class would be FooBarEditorBaz


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...