Scope of PHP variable

Asked

Viewed 96 times

2

So, I’ve been banging my head for a while now with a basic question of scope, but I couldn’t figure out why.

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

If I var_dump it before this array_filter, it will be normal, only in there does not work. What would be the real problem and how can I access the object inside the array_filter?

 foreach ($vehiclesInfo as $vInfo) {

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

1 answer

5


Is because you didn’t use the key use. It is necessary to import the variable into the scope of the 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. As in the common function, the "outside" variables do not go "into" their function.

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

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

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

};

If you need changes made within the anonymous function to affect your variable externally, you need to use the operator & prior to the same:

Thus:

    $b = 1;

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

    var_dump($b);
  • Thanks was that. I appreciate the general explanation on the subject also!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.