使用PHP相同的比较运算符和原始类型确实有意义吗?

Can't get the point of === and !== with primitive types:

$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.

The assuming that $request->getMethod() returns GET or POST (as string) and that $form->isValid() returns a boolean true or false, the following code:

if('POST' === $request->getMethod() || (false === $form->isValid())) :
endif;

Does make any sense in respect of this shorter one:

if('POST' == $request->getMethod() || !$form->isValid()) :
endif;

You have truty and falsy values in PHP. For instance, 0, '', array() are falsy values. If you use == it will match those values with the truty/falsy values:

var_dump(true == 'hello'); // true because a not empty string is a truty value
var_dump(false == 0); // true

=== will match not only the value but the type also:

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

This will become a problem when a function can return 0 or false, strpos for example.


There are also other factors with the ==. It will type cast values to a int if you compare 2 different types:

var_dump("123abc" == 123); // true, because '123abc' becomes `123`

This will be problematic if you compare a password: http://phpsadness.com/sad/47

== will sometimes have odd behavior when comparing different types. E.g. 'POST' would be considered equal to 0. That's why many people usually use ===, it avoids type-juggling problems.

In your case it shouldn't make a difference though.

They are sometimes necessary. For example when using strpos to check if a string is contained in another string you have to distinguish 0 from false.

wrong:

if(strpos($haystack,$needle))...

right:

if(strpos($haystack,$needle) !== false)...

although it may not be needed,

(false===$form->isValid())

and

!$form->isValid()

are not the same as the first is checking to see if the value of $form->isValid() is false, while the second is checking if $form->isValid() is a falsey value, so for example if $form->isValid() returns null then the first statement will not evaluate to true while the second one will evluate to true.