无法获得具有基元类型的===
和!==
的点:
$a === $b TRUE if $a is equal to $b, and they are of the same type.
$a !== $b TRUE if $a is not equal to $b, or they are not of the same type.
假设$request->getMethod()
返回GET
或POST
(作为string
),并且$form->isValid()
返回布尔值true
或false
,则以下代码:
if('POST' === $request->getMethod() || (false === $form->isValid())) :
endif;
对于这个较短的来说有任何意义吗
if('POST' == $request->getMethod() || !$form->isValid()) :
endif;
PHP中有truty和falsy值。例如,0
、''
、array()
是错误值。如果您使用==
,它会将这些值与truty/falsy值匹配:
var_dump(true == 'hello'); // true because a not empty string is a truty value
var_dump(false == 0); // true
===
不仅与值匹配,而且与类型匹配:
var_dump(true === 'hello'); // false, true is a boolean and 'hello' a string
var_dump(false === 0); // false, false is a boolean and 0 is a string
例如,当函数可以返回0
或false
、strpos
时,这将成为一个问题。
CCD_ 18也有其他因素。如果比较两种不同的类型:,它将向int
键入强制转换值
var_dump("123abc" == 123); // true, because '123abc' becomes `123`
如果您比较密码,这将是有问题的:http://phpsadness.com/sad/47
它们有时是必要的。例如,当使用strpos
检查一个字符串是否包含在另一个字符串中时,必须区分0
和false
。
错误:
if(strpos($haystack,$needle))...
右图:
if(strpos($haystack,$needle) !== false)...
==
在比较不同类型时有时会有奇怪的行为。例如,'POST'
将被认为等于0
。这就是为什么很多人通常使用===
,它避免了类型转换问题。
不过,在你的情况下,这应该没有什么不同。
尽管可能不需要,
(false===$form->isValid())
和
!$form->isValid()
与第一个语句不同,第一个语句是检查$form->isValid()
的值是否为假,而第二个语句是查看$form->isValid()
是否为假值,因此,例如,如果$form->isValid()
返回null
,则第一个语句将不会求值为真,而第三个语句将求值为真。