PHP if语句 - 逻辑

时间:2015-10-15 00:18:29

标签: php if-statement logic logical-operators

some_function($input)返回整数23

$other_int的值不等于23

代码段1

if ($int = some_function($input) && $int != $other_int) {...}

代码段2

$int = some_function($input);
if ($int != $other_int) {...}

我编写了代码片段1,认为if语句在上述条件下会返回true。我错了。

代码段2中的if语句为真。

为什么?

5 个答案:

答案 0 :(得分:4)

因此,if a子句中的赋值就是一个错误的做法。那就是说,你没有指定你认为自己的样子。这就是你实际在做的事情:

$int = (some_function($input) && $int != $other_int);

评估为true。要获得所需的结果,请将代码更改为

if (($int = some_function($input)) && ($int != $other_int)) {...}

但实际上,不要在if()语句中分配变量。

答案 1 :(得分:3)

正如其他人所提到的,&&的优先级高于分配优先级,因此您需要在之前执行的逻辑操作。

您可以使用&&代替andandor的优先级低于分配优先级,适用于此类情况。

if ($int = some_function($input) and $int != $other_int)

答案 2 :(得分:1)

&&!=的优先级高于赋值运算符=

请参阅http://www.php.net/manual/en/language.operators.precedence.php

所以在条件内:

if ($int = some_function($input) && $int != $other_int) {...}

它执行!=然后执行&&,但$int尚未初始化(假设您尚未在条件之外初始化它),所以右边side !=总是返回false。

答案 3 :(得分:0)

您无法在if语句中分配这样的值,并在同一语句中比较该值

https://3v4l.org/FlE6u

<?php

function somefunc() {
    return 23;
}

if($int = somefunc() && $int == 23) {
    echo 'Equal';
} else {
    echo 'Not Equal';
}
echo "\n";
var_dump($int);

你会注意到错误

  

注意:未定义的变量:第7行的/ in / GHVK中的int

最后$intfalse。将其分配到if

之外

答案 4 :(得分:0)

有趣的是,变量不能在if语句的条件下初始化和使用。您可能已经发现了php的错误/功能。

function some_function()
{
    return 23;
}

$intA = 0;
if ($intA = some_function()
    && $intA != $other_int
) {
    echo 'hello world!'; // works fine
}

if ($intB = some_function()
    && $intB != $other_int
) {
    echo 'hello world!'; // PHP Notice:  Undefined variable: intB
}