为什么在 if 语句中使用 : 而不是 {

Why use : instead of { in if statements

人们为什么使用

if(condition) :
    /*do something*/
else:
    /*do something else*/
endif;

而不是

if(condition) 
{
    /*do something*/
} 
else
{
    /*do something else*/
}

哪一个比另一个好?我也应该习惯什么?

这属于编码风格的范畴。有些人喜欢使用方括号,有些人喜欢使用“:end...”符号。后者的优势更多地是使用 PHP 条件和循环,其中有输出到 HTML。例如,

//Pure PHP with brackets
<?php
if ($condition) {
   echo "output";
}?>

//PHP and HTML with brackets
<?php
if ($condition) {?>
   output
<?php } ?>

//PHP and HTML with ":end..." notation
<?php if ($condition):?>
   output
<?php :endif ?>

有些人更喜欢最后一个,因为“:endif”给出了匹配控制结构时要查找的打开结构的线索。括号可以匹配任何其他括号,但 ":endif" 只能匹配 "if" 结构。你可以使用它取决于你的风格。