php Laravel foreach变量循环作用域

thtygnil  于 2023-01-24  发布在  PHP
关注(0)|答案(3)|浏览(168)

当我使用Laravel刀片文件foreach循环时,变量在foreach循环之后是可访问的,而变量的作用域应该仅在循环内

@foreach($user->referral as $ref)
  <tr>
    <td>{{ $ref->referral_amount }}</td>
    <td>{{ $ref->status }}</td>
  </tr>
@endforeach

$ref:此变量可在@endforeach之后的endforeach循环外部访问

brjng4g3

brjng4g31#

the foreach docs开始:

    • 警告**

$value的引用和最后一个数组元素即使在foreach循环后仍保留,建议通过unset()销毁
因此,如果要销毁引用,请执行以下操作:

<?php unset($ref); ?>

或者:

@php unset($ref); @endphp
rfbsl7qr

rfbsl7qr2#

建议通过unset()销毁

@php unset($ref); @endphp
xyhw6mcr

xyhw6mcr3#

根据你的问题,你可以使用php的unset()方法来销毁一个变量。
为此,您可以在foreach循环之后在blade文件中使用这种类型的代码。

<?php
// destroy a single variable
unset($foo);

// destroy a single element of an array
unset($bar['quux']);

// destroy more than one variable
unset($foo1, $foo2, $foo3);
?>

@php
// destroy a single variable
unset($foo);

// destroy a single element of an array
unset($bar['quux']);

// destroy more than one variable
unset($foo1, $foo2, $foo3);
@endphp

相关问题