David Rodrigues David Rodrigues - 7 months ago 21
PHP Question

PHP: alternative to use() to non-anonymous functions

You can do this:

$external = 1;
$change = function($number) use(&$external) {
$external = $number;
};

$change(5);
echo $external; //> 5


But you can not do this:

$external = 1;
function change($number) use(&$external) {
$external = $number;
}


You'd get:


Parse error: syntax error, unexpected 'use' (T_USE), expecting '{'.


What are alternatives?

Answer

use() is only used in closures to inherit variables from the parent scope. From the manual:

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.

If you want to use a variable by reference in a regular function use:

$external = 1;

function change($number, &$external) {
    $external = $number;
}
change(5, $external);

Or to not pass it use it as a global (if $external is in global scope):

$external = 1;

function change($number) {
    $GLOBALS['external'] = $number;
}
change(5);