PHP条件,需要括号吗?

2022-08-30 13:33:46

我刚刚浏览了一个论坛,有人问他们在网络上找到的PHP文件。它在代码中有几个这样的位置:

if ($REMOTE_ADDR == "") $ip = "no ip"; else $ip = getHostByAddr($REMOTE_ADDR);

我一直认为,如果条件为真,则需要用括号来包含您要执行的操作。是否有其他选择,例如,如果它在同一行上,则不这样做?

还有另一行这样的:if ($action != ""): mail("$adminaddress","Visitor Comment from YOUR SITE",

我的直觉是说这行不通,但我也不知道它是否是一个过时的PHP文件,它曾经工作过?


答案 1

你可以做 if else 语句,如下所示:

<?php
if ($something) {
   echo 'one conditional line of code';
   echo 'another conditional line of code';
}


if ($something) echo 'one conditional line of code';

if ($something)
echo 'one conditional line of code';
echo 'a NON-conditional line of code'; // this line gets executed regardless of the value of $something
?>



然后你也可以写 if - else 在替代语法中:

<?php
if ($something):
   echo 'one conditional line of code';
   echo 'another conditional line of code';
elseif ($somethingElse):
   echo 'one conditional line of code';
   echo 'another conditional line of code';
else:
   echo 'one conditional line of code';
   echo 'another conditional line of code';
endif;
?>



使用备用语法,您也可以退出解析模式,如下所示:

<?php
if ($something):
?>
one conditional line of code<br />
another conditional line of code
<?php
else:
   echo "it's value was: $value<br />\n";
?>
another conditional line of code
<?php
endif;
?>

但是这变得非常混乱,非常快,我不建议使用它(也许除了模板逻辑)。



并使其完整:

<?php
$result = $something ? 'something was true' : 'something was false';
echo $result;
?>

equals

<?php
if ($something) {
   $result = 'something was true';
} else {
   $result = 'something was false';
}
echo $result;
?>

答案 2

更详细地说,大括号是可选的原因是语法如下所示:

if(CONDITION) BLOCK
[elseif(CONDITION) BLOCK]
[else BLOCK]

BLOCK 可以是单个语句:

foo();

或者它可以是一组大括号括起来的语句:

{
    foo();
    bar();
}

推荐