PHP条件,需要括号? [英] PHP conditionals, brackets needed?

查看:19
本文介绍了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";否则 $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","来自您网站的访客评论",

我的直觉是说这行不通,但我也不知道它是否是一个过时的 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?

推荐答案

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

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 />
";
?>
another conditional line of code
<?php
endif;
?>

但这很快就会变得非常混乱,我不推荐使用它(可能除了模板逻辑).

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天全站免登陆