I love PHP, I really do… just, sometimes you fall into these situations where you just can’t help bang your head against the table until even the table starts bleeding.
I’m currently working on a blog series about intelligent caching with PHP. During the preparation for this I had to create a framework which could demonstrate the caching concepts I was going to be discussing, and what better than using namespaces for it. Namespaces makes auto loading easy as pie, they give you an incredible freedom in class naming due to the extra encapsulation layer and in general they’re just brilliant. Except for this.
$controller = '\Evil\Controller\News'; $data = $controller::dataKeyInvalidates($invalidate);
It simply wouldn’t work. I was certain it worked fine without namespaces so for kicks I tried this:
$data = \Evil\Controller\News::dataKeyInvalidates($invalidate);
And it ran without problems. Fun. What eventually let me figure out what was going on was by echoing the variable passed to my auto loader. When I used a variable to reference the class name the auto loader was passed “\Evil\Controller\News” when I didn’t the auto loader was passed “Evil\Controller\News”. Obviously some magic goes on inside PHP that translates \Evil\Controller\News into “Evil\Controller\News”. Setting $controller to ‘Evil\Controller\News’ made it work perfectly fine.
So to recap this:
// Does not work. $controller = '\Evil\Controller\News'; $data = $controller::dataKeyInvalidates($invalidate); // Works. $controller = 'Evil\Controller\News'; $data = $controller::dataKeyInvalidates($invalidate); // Works. $data = \Evil\Controller\News::dataKeyInvalidates($invalidate); // Does not work. $data = Evil\Controller\News::dataKeyInvalidates($invalidate);


Twitter
LinkedIn