我正在寻找更聪明的方法来解决我所谓的if-else-finally案例.
案例
根据不同的条件,对象的属性需要不同的值.仅当此属性已更改时,才会将对象保留为DB.
示例(伪代码)
if _condition-A_ then
set object.property to value-A
else if _condition-B_ then
set object.property to value-B
else if _condition-C_ then
set object.property to value-C
finally
object.persist()
Run Code Online (Sandbox Code Playgroud)
我的解决方案
$changed = false;
if ($conditionA) {
$changed = true;
$this->property = 'A';
} elseif ($conditionB) {
$changed = true;
$this->property = 'B';
} elseif ($conditionC) {
$changed = true;
$this->property = 'C';
}
if ($changed) {
$this->save();
}
Run Code Online (Sandbox Code Playgroud)
有没有更好/更智能的解决方案呢?该switch-case-default构造是不可能的,因为条件是由每个if陈述中不同的较小的部分条件组合而成的.
Seb*_* C. 10
你可以$changed = true;通过这种方式避免重复:
$changed = true;
if ($conditionA) {
$this->property = 'A';
} elseif ($conditionB) {
$this->property = 'B';
} elseif ($conditionC) {
$this->property = 'C';
} else {
$changed = false;
}
if ($changed) {
$this->save();
}
Run Code Online (Sandbox Code Playgroud)