< / >

This is a blog by about coding and web development.

Anonymous functions in PHP 5.3

Posted on in

The PHP wiki has a great developer walkthrough of the hows and whys of the new lambda in PHP 5.3. I’ve been digging around for something like this for a while. There are some important distinctions about the way PHP lambdas work, especially if you’re used to closures in languages like JavaScript.

Highlights:

  • Lambdas do not automatically inherit surrounding scope. You must specify the variables you want to be available to the method:
$foo = 1;
      $bar = function() use($foo) {
          echo "$foo\n";
      };
  • Lambdas cannot be invoked directly when assigned to an object property:
$foo = new stdClass();
      $foo->bar = function() {
          echo "hello, world!\n";
      };
      $foo->bar(); // will trigger an error

      // assign it to a temporary variable instead
      $bar = $foo->bar;
      $bar();
  • Lambdas will throw an error when serialized
  • Lambdas have no $this scope
blog comments powered by Disqus