PHP为什么要比较(null === $ variable)而没有($ variable === null)? [英] PHP why (null === $variable) and not ($variable === null) in comparison?

查看:80
本文介绍了PHP为什么要比较(null === $ variable)而没有($ variable === null)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读Symfony2代码时,我多次遇到了这种比较

if (null === $variable ) { ... }

我使用

if ($variable === null ){ ... }

因为我认为它更具可读性.

使用第一种表示法后面有智慧吗?

解决方案

它有助于防止意外分配:

if ($foo = null) { ... }

不会导致解析错误,而

if (null = $foo) { ... }

第一个示例: http://sandbox.onlinephpfunctions.com/code/fff14c285a18a7972a3222ff5af08da825c10 http://sandbox.onlinephpfunctions.com/code/118d494c17381d8e129ba005465bf84d9b8819bdaWhen reading Symfony2 code I came across this comparaison many times

if (null === $variable ) { ... }

I use

if ($variable === null ){ ... }

because I see it more readable.

Is there a wisdom behind using the first notation ?

解决方案

It helps prevent accidental assignments:

if ($foo = null) { ... }

would not cause a parse error, while will

if (null = $foo) { ... }

1st example: http://sandbox.onlinephpfunctions.com/code/fff14c285a18a7972a3222ff5af08da825760c10 2nd example: http://sandbox.onlinephpfunctions.com/code/118d494c17381d8e129ba005465bf84d9b8819bd

这篇关于PHP为什么要比较(null === $ variable)而没有($ variable === null)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆