Search code examples
phpcallbackscope

Access global variable inside the scope of an array function


I'm trying to write a filter script using an array filter function in PHP using the lambda syntax.

This achieves what I want to do, but it looks like it can be optimised:

$offersReceivedProcessedByItem = array();
  foreach ($this->currentSessionUser->items as $item) {
    $receivedOffersOnItem = array();
    foreach ($offersReceived as $offerReceived) {
     if ($offerReceived->item->id === $item->id) {
       $receivedOffersOnItem[$offerReceived->id] = $offerReceived;
     }
    }
  offersReceivedProcessedByItem[$item->id] = $receivedOffersOnItem;
}

(for each item a user has, filter through the offersReceived array and add the offer to a new array if it has an equal id, if that makes sense?!).

Here's what I'm trying:

$offersReceivedProcessedByItem = array();
foreach ($this->currentSessionUser->items as $item) {
   $receivedOffersOnItem = array_filter($item->offers, function($offer){
     return $offer->item->id === $item->id;
   });
   $offersReceivedProcessedByItem[$item->id] = $receivedOffersOnItem;
}

But I'm getting that $item is undefined, I expect it's closed scope so I tried passing $item as another argument but then I'm getting 'missing argument 2'.

I tried this using the relational approach built into Fuel but PHP eats too much memory and fails.


Solution

  • A closure doesn't know anything about the environment it is created it unless you tell it

    $receivedOffersOnItem = array_filter($item->offers, function($offer) use($item){
       return $offer->item->id === $item->id;
    });
    

    Notice the use-statement

    A link to the manual http://php.net/functions.anonymous#example-119