我需要创建一个变量,它是多个值的总和。我有大约25个值要加在一起——下面是一个小片段。下面的方法是可行的,但用+
将所有值串在一起似乎有点脏。还有别的办法吗?
// Calculate Modification Points
$trackPTS = $this->track ? 20 : 0;
$shockTowerPTS = $this->shock_tower ? 10 : 0;
$loweringPTS = $this->lowering ? 10 : 0;
$camberPTS = $this->camber ? 20 : 0;
$monoballPTS = $this->monoball ? 10 : 0;
$tubeFramePTS = $this->tube_frame ? 100 : 0;
$pasmPTS = $this->pasm ? 20 : 0;
$rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;
$totalModificationPoints = $treadWearPoints + $trackPTS + $shockTowerPTS + $loweringPTS + $camberPTS + $monoballPTS + $tubeFramePTS + $pasmPTS + $rearAxleSteerPTS;
这是做同样事情的另一种方法。
$totalModificationPoints = 0; //initial value
$totalModificationPoints += $trackPTS = $this->track ? 20 : 0;
$totalModificationPoints += $shockTowerPTS = $this->shock_tower ? 10 : 0;
$totalModificationPoints += $loweringPTS = $this->lowering ? 10 : 0;
$totalModificationPoints += $camberPTS = $this->camber ? 20 : 0;
$totalModificationPoints += $monoballPTS = $this->monoball ? 10 : 0;
$totalModificationPoints += $tubeFramePTS = $this->tube_frame ? 100 : 0;
$totalModificationPoints += $pasmPTS = $this->pasm ? 20 : 0;
$totalModificationPoints += $rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;
我会把所有可能的类变量名放在一个数组中,然后迭代它
<?php
class Calc {
private $track = 30;
private $shock_tower = 40;
private $lowering = 10;
public function __construct() {
$keyValues = [
['track', 20],
['shock_tower', 10],
['lowering', 10],
];
$sum = 0;
foreach($keyValues as $set) {
$sum += (int) $this->{$set[0]} ?? $set[1];
}
print_r($sum);
}
}
new Calc();