-1

我正在尝试对一些代码进行故障排除,但发生了一些我无法理解的事情……我有一个$forum包含threadExists方法的对象,该方法返回找到的任何结果或其他结果的关联数组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。

4

3 回答 3

2

运算符优先级导致它被解释为这样

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
}
于 2013-07-13T15:24:04.153 回答
1

像这样阅读它:

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))
于 2013-07-13T15:22:58.247 回答
1

括号问题。您正在分配$test复合条件的值,因此它将具有一个布尔值,基于它的任一侧是否解析为真。尝试:

if (!($test = $forum->threadExists($thread_id)) || $test['topic_id'] != $topic_id) { 
于 2013-07-13T15:23:28.773 回答