Dynamic Classnames
Created: Last updated:
When you work in Zend Framework 2 (ZF2) or just PHP you may have a situation where you like to call a different class because of some dynamic content. Before PHP 5.3 and the introduction of namespaces this was simple. It is still simple but with a little pitfall.
Fully Qualified Class Name
When you like to call a class in PHP with namespaces and use a string in variable this must be a full qualified class name. Nevermind that you have set the use statement at the top of your file or that the class is even in the same namespace.
If you have string in a variable PHP will assume that is a dynamic call and that you could not have set a use statement. Therefore, it will demand the full class string or as it is known a fully qualified class name.
Example
Here is a little example for this case. Note that the namespace declarations are actually backslashes and I have to cheat with forward slashes because I cannot set them in my framework for whatever reason.
- // assume this would be your two class
- namespace My/Directions;
class Left { ... }
class Right { ... } - // this would be some code calling either of the classes
- use My/Directions;
- if ( 'left' === $direction ) {
$classname = 'Left';
} else {
$classname = 'Right';
} - // the following will trigger an error because it cannot be resolved
- $object = new $classname();
- // and that's how you have to set the variable
- $fullyqualified_classname = 'My/Directions'.$classname;
$object = new $fullyqualified_classname();
So keep in mind: Classes, constants and functions must be referenced as fully qualified class name strings when you use namespaces in PHP.