PHP本身是否支持连接和析取? [英] Does PHP support conjunction and disjunction natively?
问题描述
Javascript使用连接和析取运算符。
Javascript employs the conjunction and disjunction operators.
如果可以将其评估为:false,则返回左操作数,如果是连接( a&& b),或者在析取的情况下为真(a || b);否则返回右操作数。
PHP中是否存在等效运算符?
Do equivalent operators exist in PHP?
推荐答案
PHP支持短路评估,与JavaScript的结合略有不同。我们经常看到使用短路评估来测试PHP中MySQL查询结果的示例(即使不是很好的做法):
PHP supports short-circuit evaluation, a little different from JavaScript's conjunction. We often see the example (even if it isn't good practice) of using short-circuit evaluation to test the result of a MySQL query in PHP:
// mysql_query() returns false, so the OR condition (die()) is executed.
$result = mysql_query("some faulty query") || die("Error");
请注意,当在PHP中存在要评估的表达式时,短路评估可以正常工作布尔运算符,它将产生一个返回值。只有当左侧为假时,它才会执行右侧。这与JavaScript不同:
Note that short-circuit evaluation works when in PHP when there is an expression to be evaluated on either side of the boolean operator, which would produce a return value. It then executes the right side only if the left side is false. This is different from JavaScript:
只需:
$a || $b
将返回一个布尔值 TRUE
或 FALSE
如果其中任何一个是真的或两者都是假的。它将 NOT 返回 $ b
的值,如果 $ a
是假的:
would return a boolean value TRUE
or FALSE
if either is truthy or both are falsy. It would NOT return the value of $b
if $a
was falsy:
$a = FALSE;
$b = "I'm b";
echo $a || $b;
// Prints "1", not "I'm b"
所以要回答问题是,PHP将对这两个值进行布尔比较并返回结果。它不会返回两者的第一个真值。
So to answer the question, PHP will do a boolean comparison of the two values and return the result. It will not return the first truthy value of the two.
在PHP中更具惯用性(如果存在惯用的PHP这样的东西)将使用三元操作:
More idiomatically in PHP (if there is such a thing as idiomatic PHP) would be to use a ternary operation:
$c = $a ? $a : $b;
// PHP 5.3 and later supports
$c = $a ?: $b;
echo $a ?: $b;
// "I'm b"
PHP 7更新
PHP 7引入了 ??
null合并运算符,它可以作为更接近于连词的近似值。它特别有用,因为它不需要你在左操作数的数组键上检查 isset()
。
Update for PHP 7
PHP 7 introduces the ??
null coalescing operator which can act as a closer approximation to conjunction. It's especially helpful because it doesn't require you to check isset()
on the left operand's array keys.
$a = null;
$b = 123;
$c = $a ?? $b;
// $c is 123;
这篇关于PHP本身是否支持连接和析取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!