Anonymous functions function() use ()

Anonymous functions in PHP may use this expression:

function($parameter) use ($value) {
}

What does it means? This function, simply use a reference to the variable $value that then returns to the parent scope. For example:

$value = 5;
$customFunction = function($parameter) use ($value)
{
    $value = $value + $parameter;
}

call_user_func ( $customFunction, 2 );

//$value = 5 + 2 (7)

Why to use a reference to the variable? See this as an illustrative example from the official PHP website:

$result = 0; 
$one = function() { 
    var_dump($result); 
}; 
$two = function() use ($result) { 
    var_dump($result); 
}; 
$three = function() use (&$result) 
{ 
    var_dump($result); 
}; 
$result++; 
$one();    // outputs NULL: $result is not in scope
$two();    // outputs int(0): $result was copied 
$three();    // outputs int(1)

Leave a Reply

Your email address will not be published. Required fields are marked *