今天我遇到了一个非常奇怪的问题。
我有一个 Controller ,我从那里向 View 发送三个变量 sections
thread
和 threads
.
在我看来,我正在使用 foreach 循环遍历所有部分,如下所示:
@foreach($sections as $i => $section)
对于每个部分,我都在创建一个 div 并给出这样的 id:
id="{{ $thread->slug }}-{{ $section->slug }}
现在在这个 div 中,我循环遍历所有线程,如下所示:
@foreach($threads as $thread)
并为每个线程创建 div。
现在的问题是,当线程循环完成存储在局部变量线程中的线程中的最后一项时,会覆盖从 View 发送的线程变量。
现在,我知道要解决这个问题,我可以将 foreach 循环中的局部变量重命名为其他名称,但我的问题是为什么会发生这种情况?为什么这个局部变量会覆盖我的全局变量?
这是我的 Controller :
public function show($slug)
{
return view('thread.show')
->with('sections', Section::all())
->with('threads', Thread::all())
->with('thread', Thread::where('slug', $slug)->first());
}
看法:
@foreach($sections as $i => $section)
<div class="tab-pane fade" id="{{ $thread->slug }}-{{ $section->slug }}">
@foreach($threads as $thread)
<div class="card mb-3">
{{--/// Some Html--}}
</div
@endforeach
</div>
@endforeach
现在这里是呈现的 html 的屏幕截图:
线程名称是第 172 页
第一个 div 的 id 呈现得很好,但看看其他两个 div 的 id
section-341
这是 threads
中的最后一项
最佳答案
but my question is why is this happening? why is this local variable overwriting my global variable
因为php无法区分
$thread
和 $thread
.虽然您可以期待变量
$thread
在 foreach($threads as $thread)
的上下文中只住在foreach
正文,在 php 中并非如此。局部变量
$thread
存在于您的 View 范围内,而不是您的循环体。由于php不区分,所以覆盖原来的。
关于php - Laravel - foreach 局部变量正在覆盖全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52469479/