PHP 条件语句,需要括号吗?
我正在浏览一个论坛,有人询问他们在网上找到的一个 PHP 文件。 代码中有几个这样的地方:
if ($REMOTE_ADDR == "") $ip = "no ip"; else $ip = getHostByAddr($REMOTE_ADDR);
我一直认为需要用括号来括起条件为真时您想要执行的操作。 是否还有其他选择,例如它是否与您不在同一行?
还有另一行是这样的: if ($action != ""): mail("$adminaddress","Visitor Comment from YOUR SITE",
我的直觉是这行不通,但我也不知道它是否是一个过时的 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);
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?
There is also another line like this:if ($action != ""):
mail("$adminaddress","Visitor Comment from YOUR SITE",
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你可以做这样的 if else 语句:
然后您还可以用替代语法编写 if - else :
使用替代语法,您也可以像这样脱离解析模式:
但这很快就会变得非常混乱,我不会推荐它的使用(除了模板逻辑)。
并使其完整:
you can do if else statements like this:
and then you can also write if - else in an alternate syntax:
with the alternate syntax you can also fall out of parsing mode like this:
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:
更详细地说,大括号是可选的原因是语法如下:
BLOCK 可以是单个语句:
也可以是大括号括起来的语句组:
To go into a little more detail, the reason that the braces are optional is that the syntax looks like:
BLOCK can be a single statement:
or it can be a brace-enclosed group of statements:
与大多数类似 C 的语法一样,大括号(不是中括号)在 PHP 中是可选的。 也许你想到的是 Perl; 对于那种形式的 if 语法来说,它们是必需的。
冒号是 PHP 支持的另一种控制结构形式。 我讨厌它,但有些人(尤其是模板系统设计者,显然)喜欢它。
Braces (not brackets) are optional in PHP, as in most C-like syntax. Maybe you're thinking of Perl; they're required there, for that form of if syntax.
The colon thing is an alternate control structure form that PHP supports. I hate it, but some people (particularly template system designers, apparently) love it.
我认为
这是有效的,但比以下内容更难阅读:
In my opinion
is valid, but much harder to read than:
9 年过去了,我很惊讶没有人提到三元运算符:
恕我直言,赋值更加清晰 - 因为它会导致变量被赋值,就像通常的变量赋值一样。
9 years on and I'm surprised no-one's mentioned the ternary operator:
Much clearer for assignment IMHO - because it leads out with the variable being assigned to, as for usual variable assignment.
是的,排除大括号是允许的,尽管我多次听到不使用该语法的两个原因:
另外,是的,冒号语法是有效的。 替代方案可以在这里找到: http://php.net/manual /en/control-structs.alternative-syntax.php
Yes, excluding the braces is allowed, although many times I have heard 2 reasons for not using that syntax:
Also, yes, the colon syntax is valid. The alternatives can be found here: http://php.net/manual/en/control-structures.alternative-syntax.php
我想不出任何语言需要这个
I can't think of any language that requires this