需要PHP条件,括号吗?

Lev*_*evi 30 php conditional brackets

我只是浏览一个论坛,有人问他们在网上找到的PHP文件.它在代码中有几个像这样的地方:

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

如果条件为真,我一直认为需要括号来包含你想要做的事情.还有其他一些选择,例如,如果它在同一条线上你没有吗?

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

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

Jac*_*cco 67

你可以做if if这样的语句:

<?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
?>
Run Code Online (Sandbox Code Playgroud)



然后你也可以用替代语法写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;
?>
Run Code Online (Sandbox Code Playgroud)



使用替代语法,您也可以脱离解析模式,如下所示:

<?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;
?>
Run Code Online (Sandbox Code Playgroud)

但是这真的非常麻烦,我不会推荐它的使用(除了模板逻辑).



并使其完整:

<?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;
?>
Run Code Online (Sandbox Code Playgroud)

  • 哇,我不知道有很多选项来构建php代码.谢谢! (2认同)
  • 如果你最后一个例子,你不需要额外的变量:echo $ something?'事情是真的':"有些事情是假的"; (2认同)

cha*_*aos 9

为了更详细一点,大括号是可选的原因是语法如下:

if(CONDITION) BLOCK
[elseif(CONDITION) BLOCK]
[else BLOCK]
Run Code Online (Sandbox Code Playgroud)

BLOCK可以是一个声明:

foo();
Run Code Online (Sandbox Code Playgroud)

或者它可以是括号括起来的一组陈述:

{
    foo();
    bar();
}
Run Code Online (Sandbox Code Playgroud)