How to access variable of enclosing function?
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
}
});
}
there are two three ways:
- use
global
, which is not an option for you - call different callbacks, depending on
$flag
- see chiborg's answer for how to do this properly with php's new lambda functions/inline callbacks -- performance overhead mentioned below will still apply though
i would go for option 2. because, there will also be a performance improvement: when doing 10000 comparisons, your flag will be checked 10000 times. when using two separate callback functions, the flag will be checked only once instead (comparison probably being the operation used most in sorting algorithms).
This is not possible without explicit passing the variable.
You have to pass $flat to the function() like function($a, $b, $flag).
精彩评论