Also, since I'm guessing a lot of people here are new to Anonymous Functions and Closures, the article sourced in my above post is very useful, and it details 3 things that one should know before implementing them.
Quote:QUIRK #1
You MUST send the function all of the variables you want bound to the scope of the Closure using the use keyword. This is different from most other languages, where this is done automatically (like in my JS example above).
Code:
$foo = 'foo';
$bar = 'bar';
$baz = function () use ($foo, $bar) {
echo $foo, $bar;
};
QUIRK #2
The bound variables are copies, of the variable, not references. If you want to be able to change the variable inside the Closure, you MUST send it by reference:
Code:
$foo = 'foo';
$bar = 'bar';
$baz = function () use (&$foo, &$bar) {
$foo = 'Hello ';
$bar = 'World!';
};
$baz();
echo $foo, $bar; // Outputs "Hello World!";
QUIRK #3
In PHP 5.3 if you are using a Closure inside of a class, the Closure will not have access to $this. You must send a reference to $this, however, you cannot send $this directly:
Code:
<?php
class Test
{
protected $foo = 'foo';
public function baz() {
// Get a reference to $this
$self = &$this;
$func = function () use ($self) {
echo $self->foo;
}
}
}
Note: Because of the way object references are handled in PHP, you do not have to send a reference to $self if you wish to modify it.