I want to set a data to a variable after a loop. But it still empty even I assign the variable inside the loop.
My code:
$hash = ''; $get_hash = Cart::session($user->id)->getContent()->each(function($cart) use($hash) { $hash = $cart->attributes->get('hash'); }); dd($hash) // returns empty
I want to set the hash from the value of $cart->attributes->get('hash')
I don’t know why it’s empty
but when I dd
inside the loop there’s a value.
Advertisement
Answer
The hash variable is not caught by reference:
$hash = ''; $get_hash = Cart::session($user->id)->getContent()->each(function($cart) use (&$hash) { $hash = $cart->attributes->get('hash'); }); dd($hash) // will not be empty
Scalar values like strings and integers are copied by value, not by reference. By explicitly doing so, changing the hash value in the closure will translate outside the scope.