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>";
}
}
塊語句的冒號形式通常保留給模板,其中明確的'endif'比右大括號更容易被發現。不要將它用於控制器/類代碼 - 一些標準化是好的。 – halfer
@meagar可以幫助我對這個問題進行重新說明,因爲您已經擱置了這個問題,或者建議瞭解最好的方法。 – ShapCyber
@ShapCyber所有的答案都會被置之度外,因爲這個問題與代碼嗅覺有關,這對於每個開發人員來說都是優先考慮的。 – fyrye