Home > Backend Development > PHP Tutorial > PHP运算符问题

PHP运算符问题

WBOY
Release: 2016-06-06 20:33:43
Original
1338 people have browsed it

为什么if ($a = 100 && $b = 200) {var_dump($a, $b);}输出bool(true) int(200)
PHP运算符问题

<code><?php if ($a = 100 && $b = 200) {
    var_dump($a, $b);
}
</code></code>
Copy after login
Copy after login

回复内容:

为什么if ($a = 100 && $b = 200) {var_dump($a, $b);}输出bool(true) int(200)
PHP运算符问题

<code><?php if ($a = 100 && $b = 200) {
    var_dump($a, $b);
}
</code></code>
Copy after login
Copy after login

&&优先级比=高,所以会$a = (100 && $b = 200),在http://php.net/manual/en/language.operators.precedence.php中有一句
Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.,虽然&&优先级高于=,但是200还是会被赋值给$b,由于100 && $b = 200均为真返回true,所以$a=true

实际上的优先级是这样的:

<code><?php if ($a = (100 && $b = 200)) {
    var_dump($a, $b);
}
</code></code>
Copy after login

所以$a是true。

赋值不是比较,你可能看错了

老生常谈的问题了

实际上是这样运行的

<code>php</code><code><br>if($a = (100 && $b = 200)){
    var_dump($a, $b);
}
</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template