Back to questions
JuniorTheoryCommon
What does the program print?
<?php
$factor = 2;
$scale = function (int $n) use ($factor) {
return $n * $factor;
};
$factor = 10;
echo $scale(3), ' ', $factor, "\n";6 10
- Expecting
30, as if the closure read$factorat call time:use ($factor)copies the value when the closure is created, so later assignments are not seen. - Expecting
use ($factor)to be extra parameters the call fills in: the list is filled once, when the closure is created, and the call passes only$n.
- What would the program print with
use (&$factor), and why? - Why does the closure need
useat all to see$factor?