Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access variable of enclosing function? [duplicate]

Tags:

php

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.

like image 345
kayahr Avatar asked Jan 25 '26 08:01

kayahr


1 Answers

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
    }
   });
}
like image 137
chiborg Avatar answered Jan 26 '26 20:01

chiborg