[英]PHP Break successive If Statements
我有一大組if語句,當其中一個為真時,則不需要測試以下if語句。
我不知道最好的辦法是什么。
我應該創建一個函數,開關還是while循環?
每個連續的if語句都是不同的,並且具有預先創建的輸入值。 我將嘗試創建一個簡單的例子來嘗試更好地解釋這個。
$total = ($val1+$val2+$val3)/$arbitaryvalue
if($total > 2){//Do Something
}
$total = ($val1+$val2)/$anothervalue
if($total > 2){//Do Something different
}
將它們放在前一個if語句的else中,這意味着如果第一個條件的計算結果為false,則唯一的運行。 如果你有很多if語句,這會變得很混亂,你的問題中的例子代表你的要求規模嗎?
$total = ($val1+$val2+$val3)/$arbitaryvalue
if($total > 2){//Do Something
}
else
{
$total = ($val1+$val2)/$anothervalue
if($total > 2){//Do Something different
}
}
if ( condition ) {
}
else if ( another_condition ) {
}
...
else if ( another_condition ) {
}
等等
決定是否使用循環取決於一個真實的例子。 如果有一個模式來設置$ total,那么我們可以使用循環。 如果不是,那么繼續執行if語句可能會更好:
if(($val1+$val2+$val3)/$arbitraryvalue > 2){
//Do Something
}
else if(($val1+$val2)/$anothervalue > 2)
{
//Do something different
}
但是,如果$ val1 + $ val2和$ anothervalue部分存在模式,則循環可能是更好的解決方案。 在我看來,你的決定還應該取決於模式是否有意義。
由於使用else
不會有益且難以維護,我建議使用一個函數。
函數將更加理想,因為一旦滿足條件,您可以使用return
退出函數。
如果在函數內調用,則return語句立即結束當前函數的執行,並將其參數作為函數調用的值返回。
下面是一個示例函數,其虛擬值設置用於演示目的:
<?php
function checkConditions(){
$val1 = 5;
$val2 = 10;
$val3 = 8;
$arbitaryvalue = 5;
$anothervalue = 4;
$total = ($val1+$val2+$val3) / $arbitaryvalue;
if($total > 2){
return 'condition 1';
}
$total = ($val1+$val2) / $anothervalue;
if($total > 2){
return 'condition 2';
}
return 'no conditions met';
}
echo checkConditions();
?>
如果要執行注釋代碼中指示的某種類型的操作,則可以在從函數返回之前執行相應的操作。
Ben Everard所說的是正確的方法,但還有許多其他解決方案:
$conditions = array(
array(
'condition' => ($val1+$val2+$val3)/$arbitaryvalue,
'todo' => 'doSomething',
),
array(
'condition' => ($val1+$val2)/$arbitaryvalue,
'todo' => 'doSomethingDifferent',
),
// ...
);
foreach ($conditions as $item)
{
if ($item['condition'])
{
// $item['todo']();
call_user_func($item['todo']);
break;
}
}
function doSomething()
{
// ...
}
function doSomethingDifferent()
{
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.