PHP的逻辑运算符是否可以像JavaScript一样工作? [英] Do PHP's logical operators work as JavaScript's?
本文介绍了PHP的逻辑运算符是否可以像JavaScript一样工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我最喜欢JavaScript的一件事是逻辑运算符非常强大:
One of the things I like the most of JavaScript is that the logical operators are very powerful:
-
&
可用于安全地提取对象字段的值,如果该对象或字段尚未初始化,则将返回null
&&
can be used to safely extract the value of an object's field, and will return null if either the object or the field has not been initialized
// returns null if param, param.object or param.object.field
// have not been set
field = param && param.object && param.object.field;
||
可用于设置默认值:
// set param to its default value
param = param || defaultValue;
PHP是否也允许这种逻辑运算符的使用?
Does PHP allow this use of the logical operators as well?
推荐答案
PHP返回 true
或 false
.但是您可以模拟JavaScript的 r = a ||b ||c
与:
PHP returns true
orfalse
. But you can emulate JavaScript's r = a || b || c
with:
$r = $a ?: $b ?: $c;
关于与",类似:
$r = ($a && $a->foo) ? $a->foo->bar : null;
这篇关于PHP的逻辑运算符是否可以像JavaScript一样工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文