Closures/Value capture: Difference between revisions
Content added Content deleted
(→{{header|Ruby}}: Add a few sentences to explain when i is local.) |
|||
Line 441: | Line 441: | ||
for ($i = 0; $i < 10; $i++) { |
for ($i = 0; $i < 10; $i++) { |
||
$funcs[] = function () use ($i) { return $i * $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 |
echo $funcs[3](), "\n"; // prints 9 |