Herman J. Radtke III

Read more of my blog or subscribe to my feed.


PHP goes functional in version 5.3

Written by Herman J. Radtke III on 13 Mar 2010

It has been said that all languages, over time, implement a dialect of lisp.  PHP appears to be no exception.  In PHP 5.3 lambda (or anonymous) functions and closures were added to the language.  These give PHP somewhat of a functional feel and can be very useful tools for solving problems.  One great example is the Lithium framework use of closures to implement filters.  Filters are an implementation of aspect oriented programming (AOP).  Other frameworks, like Zend Framework, are looking at these new functional tools to streamline complex and/or heavy components. I strongly believe that these new functional features will be the new "hotness" for PHP in the coming year. Expect quite a few conference sessions and tutorials devoted this very topic. All this talk of functional language features is great, but Lithium is still in development, Zend Framework 2.0 is a ways away, you have an upcoming project deadline and you want to know how this stuff can help you now.  Easy: go read or watch JavaScript examples.  Seriously.  Watching Douglas Crockford's videos on YUI theatre or reading through ExtJS source code can give you really good insight into the power of functional language features.  The syntax may be different, but the core ideas are the same. The new functional feel of PHP seems to have started a trend towards a unified constructor.  This has been a common practice in the JavaScript community for some time.  The great thing is that the PHP array is very similar to the JavaScript object.  In fact, the JSON extension to PHP makes them completely interchangeable.  Here is a quick example of one unified constructor implementation in PHP:
 'hi',
    'adder' => function($n) { return $n + 1; },
    'c' => 3,
    'd' => new stdClass
);

class base {
    function __construct(array $params)
    {
        foreach ($params as $key => $value) {
            $this->$key = $value;
        }
    }
}

class foo extends base { }

$foo = new foo($p);
I have a bunch of ideas (some great, some maybe not so great) that I plan on implementing using lambda functions and closures. I will be adding new components to my Crimson library and discussing them here.
Reblog this post [with Zemanta]