Professional PHP

PHP Programming, Web Development, PHP Advocacy and PHP Best Practices.
« php | tek Wrapup
Holiday Tech Support »

Closures are coming to PHP

March 22nd, 2009

Dagfinn has a post looking at using the new closure feature of PHP 5.3. He compares using foreach for iteration versus array_map. “Interesting,” he concludes, “but not necessarily better than conventional alternatives.”

I agree for that case. Consider instead, a more complicated operation that requires a setup and a tear down after.

 
setup();
operation();
teardown();
 

Now what happens if we need to be able to customize operation? That’s common enough, one way of doing this is to create a template method.

 
class MyExample {
    function operation() {}
    function setup() {}
    function teardown() {}
    function doit() {
        $this->setup();
        $this->operation();
        $this->teardown();
    }
}
 

Now, we can subclass MyExample and override operation() with custom logic. This is well and good, but what the customization we need is fairly small. Creating a new class carries a certain weight. Especially if you are religious about one class per file.

 
class MyExampleExtension extends MyExample {
    function operation() {
        // custom logic
    }
}
 

Plus, you now have to deal with some creational patterns to make sure your custom class is used in the right context.

 
$myObject = $registery->get('MyExample');
$myObject->doit();
 

So, instead of encapsulating the pattern, its also very common to just copy and paste:

 
setup();
custom_operation1();
teardown();
//...
setup();
custom_operation2();
teardown();
 

But that’s not good on the duplicate code front. So here is an alternate implementation, but using a closure anonymous function as a callback.

 
class MyExample2 {
    function setup() {}
    function teardown() {}
    function doit($operation) {
        $this->setup();
        $operation();
        $this->teardown();
    }
}
 

The advantage of MyExample2 is that extending is that the setup and teardown pattern is encapsulated in one spot. You konw that if setup is called, teardown will also be called. But, extending the operation is very light weight.

 
$myObject = new MyExample2();
$myObject->doIt(function () { /* custom logic 1 */ });
// ...
$myObject->doIt(function () { /* custom logic 2 */ });
 

There is another significant benefit to this and that is locality of reference. Here, the custom1 logic and the custom2 logic appears in context, not far away in some custom class or function declaration. So you get encapsulation and reuse for the common code parts, but without the sprawl and overhead of declaring structures that will only be used once in a context far away their declaration.

Closures and anonymous functions decrease the activation energy to write good code.

That’s not to say that closures and anonymous functions can’t be abused. If you keep seeing the same logic over and over in an anonymous block, you should probably give it a name in the form of a class, method or function.

Filed Under

  • PHP, Software Design

Related Posts

  • OOP is Mature, not Dead
  • Ruby versus PHP or There and Back Again
  • PDO versus MDB2
  • Why isn’t PHP the natural successor to Java?
  • How to Transfer Mac OS X Application Data between Computers
You can leave a response, or trackback from your own site.

18 Responses to “Closures are coming to PHP”

  1. arieh says:
    3/22/2009 at 10:56 pm

    there is a problem with what you suggest- one can never be sure of what is going on inside the method in your case. that is very bad practice as you can never really debug that king of class. not to mention that this breaches the access walls of a class. one can now do whatever he pleases with the inside of the class, messing with its behavior. arguably, this will make the entire point of using classes to maintain a debugble and maintainable behaviour impossible/meaningless. in that case, there realy is a question if objects should be used.
    then again, after reading what i wrote, im thinking that this is right if closures work the same way as they do in JS. do annonymus functions get access to class varibles and methods? if not, how can you use them inside of the object without creating a new object? passing $this? if so, does it mean that they can use it as though it is an internal access?

  2. Edwin Martin says:
    3/23/2009 at 1:48 am

    I’m sorry to tell you, but your code does not show the use of closures. Closures are about binding all variables in the current scope. Your examples have nothing to do with that.

    Your examples do show a use for lambda functions, another planned feature in PHP. If you had better read Dagfinns article, you would have known that he would get into closures in a second article.

  3. Les says:
    3/23/2009 at 11:06 am

    Sorry but I’m not convinced either…

    I must admit I don’t understand closures fully at the moment but from what I have read about them I don’t think they’re at all suitable for PHP.

    This is just one of those things from Ruby et al that seams trendy and in vogue at the moment but do we really want PHP to have that amount of bloat purely to satisfy those who are fashion led?

    Not read Dagfinns article yet but will get around to that later today but to close I don’t really see the problem with making use of a separate class anyways; if you have too many file reads then look to optimise your code base and implement a cache.

  4. nick says:
    3/23/2009 at 12:57 pm

    edwin is spot on, closures are not anonymous (lambda) functions. lambda functions allow the formation of closures, but they do not imply the same concept.

    @Les: trendy and in vogue? hardly. closures don’t come from Ruby, Groovy, Javascript or anything else so modern. closures were probably first implemented in lisp or scheme, decades ago. as far as PHP is concerned, it’s a natural and much more useful replacement for the abhorrent create_function() construct.

    closures are core building blocks of functional programming, that have tremendous power in that programming paradigm. adding closures to PHP brings some of that potential power.

  5. Jeff Moore’s Blog: Closures (& Lambda Functions) are coming to PHP : WebNetiques, LLC : Website Developers in Minneapolis, MN says:
    3/23/2009 at 9:49 pm

    [...] Moore has a new post showing an example of a feature that will be included in the upcoming PHP 5.3 release – [...]

  6. Jeff Moore’s Blog: Closures (& Lambda Functions) are coming to PHP : Dragonfly Networks says:
    3/23/2009 at 9:51 pm

    [...] Moore has a new post showing an example of a feature that will be included in the upcoming PHP 5.3 release – [...]

  7. Les says:
    3/24/2009 at 8:58 am

    @Nick

    I gather it’s procedural programmers who would benefit the most – but shouldn’t we all be striving to move towards OO anyways?

    We’ve managed well enough without them so far but as I said earlier, why do we need to jump on the bandwagon every time.

  8. nick says:
    3/24/2009 at 9:11 am

    @Les: I disagree that we’ve managed well enough, especially with respec to lambda functions, every time I want to use a function like array_map() or usort() and I am forced to either a) introduce a new function into the global scope, or b) use create_function().

    And when you introduce lambda functions into a language, then you might as well introduce closures as well because the additional cost is negligible.

    Moving towards object orientation principles also doesn’t mean one cannot avail oneself of powerful basic principles. I expect to see useful fruits of adding closures over objects.

  9. Jeff says:
    3/24/2009 at 10:37 am

    Edwin, You’re right, I did not use a closure in my example. I’ve edited the post appropriately

  10. Robert K says:
    4/16/2009 at 1:11 am

    Well it seemed to me at the time that from PHP 4 and onwards PHP was going to be solely focussed on OO programming – all well and good I suppose but not everyone seems to take to it like a duck to water.

    I for one like to use procedural programming as I know what all my functions are doing and for what they are doing it for but as Les (#7) says we should be striving towards cleaner shorter and multi-functional code.

    Possibly the good news is that (hopefully) there will always be the option to code in either one or the other.

  11. Closures are coming to PHP says:
    4/24/2009 at 2:20 am

    [...] Original post: Closures are coming to PHP [...]

  12. PHP y programación funcional: reutilización de código sin orientación a objetos… y más. says:
    5/22/2009 at 12:42 am

    [...] En Procata contestan a los dos artículos anteriores con un ejemplo donde, la programción funcional (con lambda y closures) si supone una auténtica ventaja frente a la tradicional a la hora de escribir código reutilizable y limpio. [...]

  13. PHP 5.3 and PHP 6 the future « 3wstudio says:
    8/22/2009 at 1:15 am

    [...] Programacion funcional en PHP [...]

  14. Mobile tracking says:
    11/18/2009 at 10:57 pm

    Great, I am planning to learn PHP, I used to use ASP, but since PHP is becoming more and more popular, I think PhP is the right choice, thanks.

  15. freetutorial says:
    12/28/2009 at 9:12 am

    Hi Very nice article.

    Please post more like this

  16. mark warne says:
    5/6/2010 at 3:27 am

    Great, very nice post it is very helpful to newcomers like me.

  17. kevin says:
    6/23/2010 at 7:46 pm

    the code is very useful to me, thanks very much!

  18. jessica says:
    6/23/2010 at 7:47 pm

    i said i want to learn PHP, so i will look around the all of your article! very good

Leave a Reply

Click here to cancel reply.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

code: use [code=php][/code].

Comment Preview

    Subscribe Feed
    Share Subscribe to this blog…
    Share Bookmark or share this page…
  • About

    My name is Jeff Moore. I'm a PHP programmer living in San Francico and working for a startup.

    More about me…

  • Categories (Home)

    • Agile Methods (14)
    • Mac (14)
    • Misc (17)
    • Open Source (14)
    • PHP (98)
    • Software Design (29)
    • Usability (14)
    • Web Design (20)
  • Recent Comments

    • Programming Language Trends via Google  19
      Craigslist pva, jessica, Scott [...]
    • Looking Towards the Cloud  35
      bentonville multiple listing, cosmetic dental, Sam Brodish [...]
    • PHP versus ASP  8
      Marhta Blight, Ravi, Ryan Brooks [...]
    • How to Transfer Mac OS X Application Data between Computers  59
      Website Migration, harry the computer support guy, Dotty Salvage [...]
    • Working with PHP 5 in Mac OS X 10.5 (Leopard)  157
      lehuuphuc, Robert Parthemer, Lingerie Intimate [...]
    • PHP Games  25
      jessica, Tennille Cranor at Chilli Plants, Lucas Ortell [...]
    • un-PEAR-ing  5
      jessica, Eugene Panin, Arnaud [...]
    • The Legality of Republishing RSS Feeds  23
      kevinxiao, Marissa Miscovich, Quick Student Loans [...]
    • Faster Page Loading  4
      jessica, angular cheilitis, Aaron Rosenfeld [...]
    • PDO versus MDB2  15
      jessica, kevinxiao, Gavin [...]
  • Recent Posts

    • ZendCon: Writing Maintainable PHP Code
    • Looking Towards the Cloud
    • Holiday Tech Support
    • Closures are coming to PHP
    • php | tek Wrapup
    • php | tek 2008
    • Sarah Snow Stever
    • Benchmarking PHP’s Magic Methods
    • The Endpoints of the Scale of Stupidity on Video
    • Working with PHP 5 in Mac OS X 10.5 (Leopard)
  • Site

    • Archives
    • Log in
  • Search