PHP条件语句,是否需要括号? [英] PHP conditionals, brackets needed?

查看:81
本文介绍了PHP条件语句,是否需要括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was just browsing a forum and someone asked about a PHP file they had found on the web. It has several spots like this in the code:

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

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

我一直认为如果条件为真,则需要用方括号括起来.还有其他选择,例如,如果您不在同一行上?

I have always thought brackets are needed to enclose what you want to do if the condition is true. Is there some other alternative, such as if it is on the same line you don't?

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

There is also another line like this: if ($action != ""): mail("$adminaddress","Visitor Comment from YOUR SITE",

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

My instinct is to say this wouldn't work, but I also don't know if it is an outdated PHP file and it used to work?

推荐答案

如果其他这样的语句,您可以做:

you can do if else statements like this:

<?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的替代语法:



and then you can also write if - else in an alternate syntax:

<?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;
?>



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



with the alternate syntax you can also fall out of parsing mode like this:

<?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;
?>

但是这真的很快变得非常混乱,我不建议您使用它(可能除了template-logic之外).

But this gets really messy really fast and I won't recommend it's use (except maybe for template-logic).



并使其完整:



and to make it complete:

<?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;
?>

这篇关于PHP条件语句,是否需要括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆