PHP 5.3 added support for closures, and I was wondering if you can close over a specific array element instead of the entire array.
For example, you can do this:
$a = array('a', 'e', 'i', 'o', 'u');
$f = function($b) use($a){
echo $a[2].$b;
};
$f('!'); // echos "i!"
But is there a way to only close around $a[2]? Something like this maybe:
$f = function($b) use($a[2] as $c){
echo $c.$b;
};
This doesn’t work, it gives:
Parse error: syntax error, unexpected ‘[‘, expecting ‘,’ or ‘)’
Obviously, I could do this:
$c = $a[2];
$f = function($b) use($c){
echo $c.$b;
};
But, I figured there had to be a better way than that. So, is there any way to just close around a specific variable in an array?
As the commentators already mentioned: No.
At the moment
useexpects only a T_Variable ($var) or a Reference T_Variable (&$var).But there is a patch making the use of
aspossible like in your example. It can be found on gist.Maybe this will be merged into master some time, so that it would be possible in a future release.
But i really don´t think this is a huge feature 🙂
So you have to go with your alternate solution in the meantime.