Anonymous user
Closures/Value capture: Difference between revisions
→{{header|PHP}}
(→{{header|Ruby}}: Add a few sentences to explain when i is local.) |
|||
Line 441:
for ($i = 0; $i < 10; $i++) {
$funcs[] = function () use ($i) { return $i * $i; };
}
echo $funcs[3](), "\n"; // prints 9
?></lang>
{{works with|PHP|pre-5.3}}
This method can capture value types like numbers, strings, arrays, etc., but not objects.
<lang php><?php
$funcs = array();
for ($i = 0; $i < 10; $i++) {
$funcs[] = create_function('', '$i = ' . var_export($i, true) . '; return $i * $i;');
}
echo $funcs[3](), "\n"; // prints 9
|