Adrian World Design
  • Services
    • Website Consulting
    • Startup Consulting
    • Zend Development
  • Portfolio
    • My Framework
  • Knowledge
    • Web Standards
    • PHP bare-bones
    • Zend Framework
    • Zend Framework 2
    • Git - Github
    • Search Engine Optimization
    • Web Hosting
    • Linux
    • Microsoft Windows
    • Web Browsers
    • Mobile Devices
  • About
    • Business
    • Professionally
    • Personally
  • Contact
    • Contact Form
    • Phone
    • Email
    • Messaging

Knowledge Base Overview

Dynamic Classnames

Knowledge ⇒ Zend Framework 2 ⇒ Fundamentals ⇒ Dynamic Classnames
Tweet
Share on Tumblr

Created: Jul 21, 2012, 4:01:52 PM CSTLast updated: Jul 21, 2012, 4:19:13 PM CST

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.

blog comments powered by Disqus
Prev
Next

Powered by FeedBurner Load our "Knowledge Base" feed in your RSS feeder

Follow us on Twitter
Follow us on Facebook
Follow us on LinkedIn
Follow us on Google+

All rights reserved, Adrian World Design ©2009–2021 Powered by Wejas Framework

Jump to Top