使用递归函数时的PHP引用变量



我有两个递归函数来计算期初库存和期末库存。

public function getClosingStock($previousStock, $product, $periodType, $lower, $upper)
{
$diffPeriod = 'diffIn' . Str::plural($periodType);
$addPeriod = "add{$periodType}";
$totalStocked = $this->getTotalStockInPeriod($product, $periodType, $lower);
$totalIssued = $this->getTotalIssueInPeriod($product, $periodType, $lower);
$currentStock = $previousStock + $totalStocked - $totalIssued;
if ($upper->$diffPeriod($lower) > 0)
{
$currentStock = $this->getClosingStock(
$currentStock, $product, $periodType, $lower->$addPeriod(), $upper
);
}
return $currentStock;
}
public function getOpeningStock($previousStock, $product, $periodType, $lower, $upper)
{
$subPeriod = "sub{$periodType}";
return $this->getClosingStock($previousStock, $product, $periodType, $lower, $upper->$subPeriod());
}

基本上,这两个函数计算从有界下限时间到有界上限时间的股票。例如,下限为2019年12月16日,上限为2020年3月31日。因此,他们将计算3月的开盘和收盘股票。


$lower = Carbon::parse('2019-12-16');
$upper = Carbon::parse('2020-03-31');
echo $lower->toDateString() . '<br>'; // Print out: 2019-12-16
echo $upper->toDateString() . '<br>'; // Print out: 2020-03-31
$opening = $this->getOpeningStock(
0, $product, 'month', $lower, $upper
);
echo $lower->toDateString() . '<br>'; // Print out: 2020-02-16
echo $upper->toDateString() . '<br>'; // Print out: 2020-02-29
$closing = $this->getClosingStock(
0, $product, 'month', $lower, $upper
);

问题是,在我运行getOpeningStock函数后,我的2个变量$lowerupper发生了更改,它们没有保留我一开始设置的原始值。您可以在我上面的代码中看到注释中的差异。造成差异的原因是什么?

谢谢!

克隆$lower$upper,并在克隆的副本上调用$addPeriod()$subPeriod(),然后递归传递:

public function getClosingStock($previousStock, $product, $periodType, $lower, $upper)
{
$diffPeriod = 'diffIn' . Str::plural($periodType);
$addPeriod = "add{$periodType}";
$totalStocked = $this->getTotalStockInPeriod($product, $periodType, $lower);
$totalIssued = $this->getTotalIssueInPeriod($product, $periodType, $lower);
$currentStock = $previousStock + $totalStocked - $totalIssued;
if ($upper->$diffPeriod($lower) > 0)
{
$cloned_lower = clone $lower;
$currentStock = $this->getClosingStock(
$currentStock, $product, $periodType, $cloned_lower->$addPeriod(), $upper
);
}
return $currentStock;
}
public function getOpeningStock($previousStock, $product, $periodType, $lower, $upper)
{
$subPeriod = "sub{$periodType}";
$cloned_upper = clone $upper;
return $this->getClosingStock($previousStock, $product, $periodType, $lower, $cloned_upper->$subPeriod());
}

最新更新