Skip to content

variable references & in Laravel

In the following code, I noticed &$list is passed by reference in the loop, however $user and $request are passed by variables. Passing $list directly to the loop won’t change $list outside the loop scope.

    public function index(Request $request, User $user)
        $list = collect();
        $someRelations()->each(function ($val) use (&$list, $request, $user) {
            // mutate $list

Why is this?



Actually its the core PHP functionality rather than Laravel itself, basically when you are passing variables without reference, it actually clone the variable with the same name but in different locations. So, if you make any changes to it, there will be no changes to the value of the variable outside the scope.

Without reference

$x = 10;
(function() use ($x){
    $x = $x*$x;
    var_dump($x); // 100
var_dump($x); // 10

But, if you pass the value by reference, instead of creating a new variable, it provides the reference to the same original variable. So, any changes made inside the function will change the value of the variable outside scope as well.

Pass by reference

$y = 10;
(function() use (&$y){
    $y = $y*$y;
    var_dump($y); // 100
var_dump($y); // 100

To know more about it you could visit,