In order to initialize a variable in the parent scope from within a closure, I can do this:
$f = function () use (&$a) {
$a = 1;
};
$f();
$a === 1; // true
My question is, is this a side-effect or is it intended behaviour I can rely on in the future? I know I can simply add $a = null
before defining the closure, but this can get ugly with a lot of variables.
It is intended behavior due to the reference, from the manual PHP : What References Do:
Note:
If you assign, pass, or return an undefined variable by reference, it will get created.
Even before calling the function the variable is created and set to NULL
since use
imports the variable at the time of function creation. Before the function definition you get a Notice: Undefined variable: a:
var_dump($a);
$f = function () use (&$a) {
//$a = 1;
};
var_dump($a);
$f();
var_dump($a);
Yields:
Notice: Undefined variable: a
NULL
NULL
NULL