PHP Namespaces and Closures

PHP 5.3 comes with two very important features: Namespaces and Closures.

Namespaces

Namespaces allow you to compartmentalise your classes, constants and functions.

This can prevent conflicts between your code and third-party code. Third-party code could be a blog or a forum that you've installed on your website.

I had a conflict when adding wordpress to a website. Wordpress was complaining that the is_email function already existed. This is because is_email is a function in my library that I use all the time to determine if an email address is valid. My only choice was to either rename one of the functions - or get wordpress to use mine. Changing anything like that in wordpress is not feasible - as any changes I make would need to be redone every time wordpress is updated. So I ended up renaming my function to is_valid_email and then going through all my code and referring it to the new, less snappier function name. Not an ideal solution by any means.

Namespaces would have been a much better solution as you can effectively say - this is my code and this is wordpress and put them in their own little namespace box so that they can't kill each-other.

Closures / Anonymous functions

For ages I didn't know what lexical closures meant - even though I use them all the time. Lexical closures is a complicated name for anonymous functions. Anonymous functions have been in javascript for a very long time.

In javascript you would typically use an anonymous function on an event handler.
Here's some prototype code using a standard function:

$('foo').observe('click', hello); function hello() { alert('hello'); }

Here's the same code with an anonymous function:

$('foo').observe('click', function(){ alert('hello'); });

The hello function is only ever going to used as an event handler - so we don't need to give it a name. This means that the code is more concise and we haven't had to spend time thinking of a good function name.

This is an example of how they are implemented in PHP - taken from the PHP manual:



10/03/2010 permalink | Posted in web development | 32 Comments »


Bookmark and Share

About me

Adam Jimenez is a freelance web developer who has been professionally developing websites since 2000.

Find me


Projects


Archive