RSS
 

Posts Tagged ‘php 5.3’

PHP 5.3 Dynamic Namespace Resolution

10 Apr

As PHP continues evolving, it just keeps getting better and better. One of the features added in version 5.3 is support for namespaces. If you’ve started trying to actually use PHP namespaces, you’ve probably run into some of the more obvious quirks that require you to either retrofit your code or implement a workaround. I started with the former before realizing that thanks to the namespace feature itself, a simple set of workarounds could do the job.

Specifically, I’m referring to the fact that namespace resolution happens at compile time, which means that if you attempt to reference a namespaced class or method as a string, it won’t be recognized unless that string explicitly includes the namespace name. The most apparent case is when calling class_exists(). For example, let’s say you define class Settings in namespace OssumCMS:

namespace OssumCMS;

class Settings {
  const MEMCACHED_ADDR = 'none';
  public static function do_something() {
  }
}

In your code, you might want to do some things like:

// ...
if (class_exists('Settings'))
  if (@constant('Settings::MEMCACHED_ADDR') != 'none')
    call_user_func(array('Settings', 'do_something'));

But that would never work because class Settings is defined within namespace OssumCMS. PHP resolves namespaces at compile time, so when class_exists(), constant(), and call_user_func() are called at run time, they won’t ever find class Settings because it’s checking only the global namespace. Read the rest of this entry »

 
2 Comments

Posted in PHP