我有这个函数迭代一个集合,并将一些值添加到每个函数之外的变量$totalSaleValue
:
public function totalSaleValue()
{
$totalSaleValue = 0;
$this->products->each(function ($item, $key) use ($totalSaleValue){
if (!empty($item->sale_price)) {
$totalSaleValue += $item->sale_price * $item->pivot->stock;
}
});
return $totalSaleValue;
}
但总是$totalSaleValue
返回0
。
有什么问题?
通过引用传递变量:
$this->products->each(function ($item, $key) use (&$totalSaleValue) {