在作为条件一部分的变量赋值过程中丢失数组


Losing array during variable assignment as part of a condition

我正在尝试对一些代码进行故障排除,但发生了一些我无法理解的事情。。。我有一个包含threadExists方法的$forum对象,该方法返回找到的任何结果的关联数组,否则返回false

以下将按预期打印阵列:

if (!$test = $forum->threadExists($thread_id)) {
    // do something
}
echo '<pre>';
var_dump($test);
echo '</pre>';
exit;

然而;通过添加条件,屏幕将简单地打印bool(true):

if (!$test = $forum->threadExists($thread_id) || $test['topic_id'] != $topic_id) {
    // do something
}
echo '<pre>';
var_dump($test);
echo '</pre>';
exit;

为什么阵列丢失了?

我使用的是PHP 5.4.12。

运算符优先级导致其被解释为如下

if (!($test = ($forum->threadExists($thread_id) || $test['topic_id'] != $topic_id))) {
    // do something
}

更清楚地说,

$test = $forum->threadExists($thread_id) || $test['topic_id'] != $topic_id;
if (!$test) {
    // do something
}

您可以使用括号强制执行正确的行为

if (!($test = $forum->threadExists($thread_id)) || $test['topic_id'] != $topic_id) {
    // do something
}

就我个人而言,我会这样写,因为我讨厌阅读时有点棘手的代码

$test = $forum->threadExists($thread_id);
if (!$test || $test['topic_id'] != $topic_id) {
    // do something
}

这样读:

if(!$test = $forum->threadExists($thread_id) || $test['topic_id'] != $topic_id)
  1. $forum->threadExists($thread_id) || $test['topic_id'] != $topic_id分配给$test
  2. 否定并检查$test的值

由于$forum->threadExists($thread_id) || $test['topic_id'] != $topic_id的计算结果为true,因此您可以将true分配给$test

修复是:

if((!$test = $forum->threadExists($thread_id))||($test['topic_id'] != $topic_id))

圆括号问题。您将复合条件的值分配给$test,因此它将具有一个布尔值,该值取决于它的任一侧是否解析为true。尝试:

if (!($test = $forum->threadExists($thread_id)) || $test['topic_id'] != $topic_id) {