添加到laravel中每个方法内的变量

问题描述 投票:1回答:1

我有这个函数迭代一个集合,并将一些值添加到每个函数之外的变量$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

有什么问题?

php laravel
1个回答
4
投票

通过引用传递变量:

$this->products->each(function ($item, $key) use (&$totalSaleValue) {
© www.soinside.com 2019 - 2024. All rights reserved.