在php中使用===代替==的重要性!

发布于 2024-09-06 18:12:07 字数 470 浏览 11 评论 0原文

直到今天我才注意到并发现使用 === 运算符的重要性。您可以在下面的示例中看到它:

$var=0;
if ($var==false) echo "true"; else echo "false";  //prints true
$var=false;
if ($var==false) echo "true"; else echo "false";  //prints true
$var=0;
if ($var===false) echo "true"; else echo "false";  //prints false
$var=false;
if ($var===false) echo "true"; else echo "false";  //prints true 

问题是,是否有任何情况下使用 === 运算符而不是 == 运算符很重要?

Today only I have noticed and found out the importance of using === operator. You can see it in the following example:

$var=0;
if ($var==false) echo "true"; else echo "false";  //prints true
$var=false;
if ($var==false) echo "true"; else echo "false";  //prints true
$var=0;
if ($var===false) echo "true"; else echo "false";  //prints false
$var=false;
if ($var===false) echo "true"; else echo "false";  //prints true 

The question is that, are there any situations where it is important to use === operator instead of using == operator?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

旧人哭 2024-09-13 18:12:07

当然,仅举一个例子: array_search()

警告

此函数可能返回布尔值 FALSE,但也可能返回计算结果为 FALSE 的非布尔值,例如 0 或 <代码>“”。请阅读有关布尔值的部分以获取更多信息。使用===运算符来测试该函数的返回值。

基本上,如果您使用任何成功时返回值但失败时FALSE返回值的函数,您应该使用===检查结果以确保(不然为什么会有一个大的红色警告框?;))


进一步的例子: next(), current()
或者也提到字符串函数 strpos()stripos() 等甚至

substr() 虽然它是没有明确提及:

返回提取的字符串部分,失败时返回 FALSE。

但如果提取的部分是“0”怎么办?它的计算结果也为 FALSE,但这不是错误。

Of course, just one example: array_search()

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Basically if you use any function that returns a value on success but FALSE on failure, you should check the result with === to be sure (otherwise why would there be a big red warning box? ;))


Further examples: next(), current()
or as also mentioned string functions as strpos(), stripos(), etc.

Even substr() although it is not mentioned explicitly:

Returns the extracted part of string or FALSE on failure.

But what if the extracted part is"0"? It also evaluates to FALSE, but it is not an error.

滥情空心 2024-09-13 18:12:07

始终选择 === 而不是 ==,除非您绝对确定需要 ==,因为 ==不具有传递性。反过来,这对于您对代码的推理也很重要。

考虑下面的代码片段

if ( $a == $b && $b == $c ) {
    // [1] assert: $a == $c
}

任何人都会从 if 条件推断出断言 $a == $c 为真,因为我们已经习惯了可传递的相等关系。但这不适用于 ==,反例:

$a = "0";
$b = 0;
$c = null;

现在想想我们在编写代码时(有时是无意识地)做出这种假设的频率。这可能会导致严重的错误。

Always choose === over == except you're absolutely sure you need ==, because == is not transitive. And that in turn is important for your reasoning about your code.

Consider the following code snippet

if ( $a == $b && $b == $c ) {
    // [1] assert: $a == $c
}

Anybody would infer from the if condition that the assertion $a == $c is true because we are so used to the equality relation being transitive. But that doesn't hold for ==, counter example:

$a = "0";
$b = 0;
$c = null;

Now think about how often we make (at times unconsciously) that assumption while writing code. That could lead to serious bugs.

满身野味 2024-09-13 18:12:07

strpos() 中,当找到字符串时为 0,当找到字符串时为 false失踪了。您必须使用 === 来检查差异。

In strpos() you have 0 when string is found and false when is misissing. You must use === to check difference.

棒棒糖 2024-09-13 18:12:07

===严格类型比较运算符,它不仅会检查,还会检查它们的类型,而== 仅检查是否相同。

考虑比较数字或字符串时的情况:

if (4 === 4) // same type and value
{
  // true
}

但是

if (4 == "4") // same value but different type
{
  // true
}

,因此

if (4 === "4") // same value but different type
{
  // false
}

在上述情况下,您必须做出明智的选择是使用 == 还是 ===

The === is strict type comparison operator, it will not only check values but also their type whereas == only checks whether or not values are same.

Consider a situation when you compare numbers or strings:

if (4 === 4) // same type and value
{
  // true
}

but

if (4 == "4") // same value but different type
{
  // true
}

and

if (4 === "4") // same value but different type
{
  // false
}

So in above cases, you have to make sensible choice whether to use == or ===

终弃我 2024-09-13 18:12:07

一个可能遇到麻烦的好例子是比较 0 和字符串, fx

if (0 == 'completed') {
  // evaluates as TRUE
}

不以数字开头的字符串在转换为 int 时会变成 0。当将 0 状态与字符串进行比较时,这可能会成为问题。

A good example where you can get into trouble is comparing 0 and a string, fx

if (0 == 'completed') {
  // evaluates as TRUE
}

A string not starting with a number becomes 0 when converted into an int. This can become a problem when comparing a status that can be 0 to a string.

月下伊人醉 2024-09-13 18:12:07

=== 运算符检查类型以及值是否相等。

这就是为什么 0 === false 不返回 true,因为它们不是同一类型。

The === operator checks type as well as value equality.

That's why 0 === false does not return true, as they are not of the same type.

最丧也最甜 2024-09-13 18:12:07

如果 $needle 不存在于 $haystack 中,strpos($needle,$haystack) 及相关函数将返回 false,如果 $needle 是 $haystack 的第一个字符,则返回 0;还有很多类似的功能。
在这种情况下,使用 == 可能会给出不正确的结果,因此应始终使用 ===。该手册清楚地指出了需要这样做的地方。

strpos($needle,$haystack) and related functions will return false if $needle doesn't exist in $haystack, and 0 if $needle is the first character of $haystack; and there's a whole host of similar functions.
Using == can give you incorrect results in this case, so you should always use ===. The manual clarly identifies where this is necessary.

怪我鬧 2024-09-13 18:12:07

最近,当我编写快速 SQL 查询解析器时,我自己也遇到了这个问题。简而言之,我将引用的参数与其极端情况占位符进行比较。基本上,下面的代码让我经历了一些困难的调试时间(当然,这个例子是经过简化的)

$var = 0; // This is supplied dynamically

$someCondition = $var == '?';

$someCondition最终始终为真。 颤抖

基本上任何非严格 (==); == <字符串>比较将导致字符串转换为整数。根据输入的不同,这可能最终为 0 或字符串的 int 值(如果有的话),即使整个字符串不完全是数字。

I have recently ran into this problem myself when I was writing a quick SQL query parser. To cut the story short, I was comparing quoted parameters with their corner-case placeholders. Basically, the following code led me to some hard debugging times (the example is simplified of course)

$var = 0; // This is supplied dynamically

$someCondition = $var == '?';

$someCondition ended up being true all the time. Shiver

Basically any non-strict (==) <int> == <string> comparison will cause the string to be cast to an integer. Depending on the input, this might end up as 0 or the int-value of the string, if it has any, even if the whole string is not completely numeric.

暮年慕年 2024-09-13 18:12:07

如果比较两个数字字符串,它们将作为整数进行比较。1

var_dump("15" == "0xF"); // TRUE
var_dump("15" === "0xF"); // FALSE

并且 TRUE 间接等于FALSE 2

$a = 0;
$b = 'x';
var_dump(FALSE == $a); // TRUE
var_dump($a == $b);  // TRUE
var_dump($b == TRUE);  // TRUE
var_dump(FALSE === $a); // FALSE
var_dump($a === $b);  // FALSE
var_dump($b === TRUE);  // FALSE

If you compare two numerical strings, they are compared as integers.1

var_dump("15" == "0xF"); // TRUE
var_dump("15" === "0xF"); // FALSE

and TRUE is indirectly equal to FALSE 2

$a = 0;
$b = 'x';
var_dump(FALSE == $a); // TRUE
var_dump($a == $b);  // TRUE
var_dump($b == TRUE);  // TRUE
var_dump(FALSE === $a); // FALSE
var_dump($a === $b);  // FALSE
var_dump($b === TRUE);  // FALSE
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文