2017-04-30 27 views
0

我只是想知道是否有原因或利用花括號或不使用大括號編寫PHP片段的優勢。在PHP中使用或不使用大括號的重要性或含義是什麼?

我有這三種方法獲得序號後綴的數字。應該是什麼在這種情況下,最好的辦法

方法1:如果沒有「大括號」的「大括號」

function ordinalSuffix($n) { 
    //any number such as zero(0) should end with 'th' other than 1,2,3 which must be 1st 2nd 3nd 
    $appends = array('th','st','nd','rd','th','th','th','th','th','th'); 
    // using php modulus check if number is 11, 12 or 13 
    if ((($n % 100) >= 11) && (($n % 100) <= 13)) 
     return $n. 'th'."<br/>"; 
    else 
      return $n. $appends[$n % 10]."<br/>"; 
} 
//Example Usage 
$studentMarks=range(1,26); 
foreach($studentMarks as $key => $studentResult) 
//check for odd and even 
if(($key % 2) == 1) 
echo "<div class='dark'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>"; 
else 
echo "<div class='ligth'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>"; 

方法2:如果沒有「大括號」的「大括號」

function ordinalSuffix($n) { 
    //any number such as zero(0) should end with 'th' other than 1,2,3 which must be 1st 2nd 3nd 
    $appends = array('th','st','nd','rd','th','th','th','th','th','th'); 
    // using php modulus check if number is 11, 12 or 13 
    if ((($n % 100) >= 11) && (($n % 100) <= 13)): 
     return $n. 'th'."<br/>"; 
    else: 
      return $n. $appends[$n % 10]."<br/>"; 
    endif; 
} 
//Example Usage 
$studentMarks=range(1,26); 
foreach($studentMarks as $key => $studentResult): 
//check for odd and even 
if(($key % 2) == 1): 
echo "<div class='dark'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>"; 
else: 
echo "<div class='ligth'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>"; 
endif; 
endforeach; 

方法3:利用 「括號」 的 「大括號」

function ordinalSuffix($n) { 
    //any number such as zero(0) should end with 'th' other than 1,2,3 which must be 1st 2nd 3nd 
    $appends = array('th','st','nd','rd','th','th','th','th','th','th'); 
    // using php modulus check if number is 11, 12 or 13 
    if ((($n % 100) >= 11) && (($n % 100) <= 13)){ 
     return $n. 'th'."<br/>"; 
    } 
    else{ 
      return $n. $appends[$n % 10]."<br/>"; 
    } 
} 
//Example Usage 
$studentMarks=range(1,26); 
foreach($studentMarks as $key => $studentResult){ 
//check for odd and even 
if(($key % 2) == 1){ 
echo "<div class='dark'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>"; 
} 
else{ 
echo "<div class='ligth'>Student - (". ($key + 1) .") Result is :".ordinalSuffix($studentResult)."</div>"; 
} 
} 
+0

塊語句的冒號形式通常保留給模板,其中明確的'endif'比右大括號更容易被發現。不要將它用於控制器/類代碼 - 一些標準化是好的。 – halfer

+0

@meagar可以幫助我對這個問題進行重新說明,因爲您已經擱置了這個問題,或者建議瞭解最好的方法。 – ShapCyber

+0

@ShapCyber​​所有的答案都會被置之度外,因爲這個問題與代碼嗅覺有關,這對於每個開發人員來說都是優先考慮的。 – fyrye

回答

1

然後你從來不用擔心什麼代碼作爲條件的一部分執行。不要讓你的未來自己或任何維護這個代碼的人做出一個愚蠢的,可預防的錯誤。所需要的只是在IF語句中增加一行,而沒有大括號和意外,難以捕捉,會發生錯誤。這也更容易閱讀。可維護性總是重要的,不應忽視。

+0

是的。無支架選項應該從PHP,IMO中刪除。 – ceejayoz

相關問題