php中&$用法
在PHP中,默认情况下,函数参数是按值传递的。这意味着当你传递一个变量给函数时,函数内部操作的是这个变量的拷贝,原始变量不会改变。 而使用&$(即变量名前加&)表示按引用传递,这样函数内部操作的就是原始变量本身,而不是拷贝。因此,在函数内部对参数的任何修改都会影响到原始变量。
$total = 0;
// 2. 定义闭包外部的引用变量(关键:用引用传递)
$sum = &$total;
$grid->column('xiaoji', __('小计'))->display(function() use (&$sum) {
// 计算当前行小计
$subtotal = $this->a * $this->syzys;
// 累加当前行的值到总和(使用引用变量)
$sum += $subtotal;
return number_format($subtotal, 3);
});
// 方案一:添加底部合计行
$grid->footer(function ($query) use (&$total) {
$totalAmount = $query->sum('syzys');
// 重新计算总费用,避免直接对显示值求和
$totalQuantity=bcmul(1, $total, 3); // 精确小数计算
session(['fyxj' => number_format($totalQuantity, 3)]);
return '<tr class="table-footer-summary">
<td colspan="5" style="padding:0;">
<div style="display:flex; justify-content:flex-end; background-color:#f8f9fa; border-top:2px solid #dee2e6; padding:12px 15px;">
<div style="font-weight:bold; margin-right:20px;">总计:</div>
<div style="font-weight:bold; color:#2c3e50; margin-right:30px;">
当页总使用资源时:<span class="summary-value">'. number_format($totalAmount, 3) .'</span>
</div>
<div style="font-weight:bold; color:#e74c3c;">
当页总费用:<span class="summary-value">¥'. number_format($totalQuantity, 3) .'</span>
</div>
</div>
</td>
</tr>';
});
最近访问时间:2025-08-17 14:02:34