I'm using a callback function inside an other function and I need to access a variable from this enclosing function but don't know how to do that. Here is an example:
function outer($flag)
{
$values = array(1, 5, 3, 9);
usort($values, function($a, $b)
{
if ($flag)
{
// Sort values in some way
}
else
{
// Sort values in some other way
}
});
}
So I pass some flag to the outer function which is then used inside the sort callback function to decide how to sort the values. Yes, I know I could check the flag in the outer function instead and then call different sort functions but this is not the question.
The question is simply how can I access a variable (or parameter) of the outer function inside the callback. Using a global variable instead is not an option. A "This is not possible" answer is also acceptable if there is really no way to do it.
There is the use keyword for that. It makes the current value of the variable available in the function.
function outer($flag)
{
$values = array(1, 5, 3, 9);
usort($values, function($a, $b) use ($flag)
{
if ($flag)
{
// Sort values in some way
}
else
{
// Sort values in some other way
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With