source code bean

06 Jun, 2010

Two new features I really like in PHP 5.3

Posted by: Peter In: PHP

Namespaces
Finally PHP has support for namespaces, not one day too late! Before the days of object oriented PHP name clashes for functions was usually prevented by adding a prefix to your function names. When object oriented PHP was introduced function name clashes was less likely, but class names still had to be unique, ie you could only have one class named for example “User”. This led to the need of prefixing class names. From PHP 5.3 we no longer have to do this!


Namespaces in PHP introduced two new keywords:

  • namespace – define a namespace
  • use – Use a namespace
  • use … as – Use a namespace but give it an alias name

Late static binding

Lambda functions and closures
Lambda functions, or anonymous functions as they are called in PHP, is really something I have missed in PHP. Lambda functions are very convenient to use when you are dealing with callbacks, for example:

  1.  
  2. <?php
  3. echo preg_replace_callback(‘~-([a-z])~’, function ($match) {
  4.     return strtoupper($match[1]);
  5. }, ‘hello-world’);
  6. // outputs helloWorld
  7. ?>
  8.  


Closures are also a very welcome addition to the language. A closure is not the same thing as an anonymous method, which seem to be a widespread misunderstanding. This is the definition from wikipedia of what a closure is:

“In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be “closed over” its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself.” - Wikipedia

In PHP closures will allow us to define closures like this:

  1.  
  2. <?php
  3. $sayhito= function($name)
  4. {
  5.     printf("Hi %s\r\n", $name);
  6. };
  7.  
  8. $sayhito(‘Foo’);
  9. $sayhito(‘Bar’);
  10.  
  11. // This will print
  12. // Hi Foo
  13. // Hi Bar
  14. ?>
  15.  


Pretty sweet!



No Responses to "Two new features I really like in PHP 5.3"

Comment Form

Adwords

About

Welcome to source code bean! On this site I post stuff that I encounter in my job and spare time. The content is mostly related to .NET development, but my interest in techonology is very broad, so often you will find posts on totally different subjects!