在 if() 块中分配多个变量时出现意外行为 [英] Unexpected behavior when assigning multiple variables in if() block
问题描述
本着看到 像 Python 的and"这样的短路评估的精神在存储检查结果时我决定看看如何在 PHP 中最好地解决这个问题,但我遇到了一个问题.
In the spirit of seeing Short-circuit evaluation like Python's "and" while storing results of checks I decided to see how this could be best solved in PHP but I've run into an issue.
意外
<?php
function check_a()
{
return 'A';
}
function check_b()
{
return 'B';
}
function check_c()
{
return 'C';
}
if($a = check_a() && $b = check_b() && $c = check_c())
{
var_dump($a);
var_dump($b);
var_dump($c);
}
结果:
bool(true)
bool(true)
string(1) "C"
<小时>
我想要发生的事情的代码
<?php
function check_a()
{
return 'A';
}
function check_b()
{
return 'B';
}
function check_c()
{
return 'C';
}
// if(($a = check_a()) && ($b = check_b()) && $c = check_c()) // equivalent to line below
if(($a = check_a()) && ($b = check_b()) && ($c = check_c()))
{
var_dump($a);
var_dump($b);
var_dump($c);
}
结果:
string(1) "A"
string(1) "B"
string(1) "C"
<小时>
为什么出乎意料的例子会这样?
推荐答案
这是一个运算符优先级.赋值表达式返回分配的值,因此您希望得到 A
和 B
用于前两个操作.您获得布尔值 true
的原因是 &&
运算符的优先级高于赋值运算符,因此在原始表达式中
This is a question of operator precedence. An assignment expression returns the assigned value, so you would expect to get A
and B
for the first two operations. The reason you're getting boolean true
instead is that the &&
operator has a higher precedence than the assignment operator, so in the original expression
$a = check_a() && $b = check_b() && $c = check_c()
$a
获取check_a() && 的值$b = check_b() &&$c = check_c()
,
$b
获取check_b() && 的值$c = check_c()
,
和$c
得到check_c()
的值.
表达式 check_a() &&$b = check_b() &&$c = check_c()
和 check_b() &&$c = check_c()
return boolean true
,因为使用 &&
运算符会导致表达式被评估为布尔值,并且所有组件由 &&
连接的表达式的计算结果为 true
.
The expressions check_a() && $b = check_b() && $c = check_c()
, and check_b() && $c = check_c()
return boolean true
, because the use of the &&
operator causes the expressions to be evaluated as booleans, and all components of the expressions joined by &&
evaluate to true
.
为了得到你期望的结果,你可以像你一样添加括号,或者你可以使用and
逻辑运算符而不是&&
,因为它的优先级低于赋值运算符.
To get the results you expect, you can add parentheses as you did, or you can use the and
logical operator instead of &&
, because it has a lower precedence than the assignment operator.
if($a = check_a() and $b = check_b() and $c = check_c()) {
这篇关于在 if() 块中分配多个变量时出现意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!