Scope of PHP variable

2

So, I've been banging my head for some time now with a basic scope question, but I could not figure out why.

In the function below, I'm trying to access a position of the object that is running at the time of Foreach, though it is giving the $ vInfo variable as Undefined.

If I give a var_dump on it before this array_filter, it goes normal, only in there it does not work. What would be the real problem and how do I get access to the object inside the array_filter?

 foreach ($vehiclesInfo as $vInfo) {

        $splitOpenedIdleEvents = array_filter($openedEvents, function($o){ 
            return $o->vehicleid == $vInfo->v_id;
        });
    
asked by anonymous 22.11.2018 / 13:16

1 answer

5

It's because you did not use the use key. It is necessary to import the variable into the scope of Closure :

foreach ($vehiclesInfo as $vInfo) {

    $splitOpenedIdleEvents = array_filter($openedEvents, function($o) use($vInfo) { 
        return $o->vehicleid == $vInfo->v_id;
    });
}

In PHP, when you create an anonymous function (also called Closure ), the scope of the function is equivalent to the scope of a common function. Just like in the common function, the "outside" variables do not go "in" to their function.

In the case of the anonymous function, it can be solved by keyword use .

If you need to pass more than one variable, you can use , to separate them as if they were parameters:

$callback = function ($x) use($a, $b, $c) {

};

If you need changes made inside the anonymous function to affect your variable externally, you need to use the & operator before it:

So:

    $b = 1;

    $callback = function ($x) use(&$b) {
         $b = 2;
    }

    var_dump($b);
    
22.11.2018 / 13:20