Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to variable in outside the map function in Laravel PHP

Tags:

php

laravel-5

public function test()
{
        $x = 10;
        $collection = collect([0, 10, 20]);

        $collection = $collection->map(function ($item, $key){

            return $item + $x;
        });
}

I want to access the $x variable within the map function: how to do it?
When I try to get the value I got this error message:

ErrorException: Undefined variable: x

like image 810
Janaka Pushpakumara Avatar asked Jan 08 '18 13:01

Janaka Pushpakumara


Video Answer


2 Answers

You need to make sure the anonymous function has access to the variable using the use keyword.

You would use it like this:

$collection = $collection->map(function ($item, $key) use ($x) {

    return $item + $x;
});
like image 118
madsroskar Avatar answered Sep 28 '22 23:09

madsroskar


public function test()
{
    $x = 10;
    $collection = collect([0, 10, 20]);

    $collection = $collection->map(function ($item) use ($x) {
        return $item + $x;
    });
}

Please note that you had return = in your code which is wrong

like image 38
meewog Avatar answered Sep 29 '22 00:09

meewog