Take care when you use ($this) in your anonymous functions (closures) – it will be copied

Anonymous functions1 (closures) in PHP 5.3 are cool. Awesome is when you can use2 any variable with it. With PHP 5.4 you can even use $this.

The problem with use is that it is making the value available in the current scope by copying2 it, thus not modifying it upwards the chain. To over come this, simply pass by reference1.

1
$anon = function(){
    // Some fancy execution right here
};
$anon();

2
$otherRandomVar = 5;
$anon = function() use ($otherRandomVar) {
    // $otherRandomVar will be made available in $anon() by copy
    // In this case it is not modifying its value in the global scope
    $otherRandomVar = 8915 + 945;
};

echo $otherRandomVar; // 5

3
$randomVar = 'abc';
$anonFuncRightHere = function() use (&$randomVar) {
    // Passing by reference will solve your issue
    $randomVar = 'cba';
};

echo $randomVar; // cba
Advertisements

Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s