What's the best practice for writing if-statement on boolean value?
function foo(boolean $bar)
{
if ($bar === false) // ...
// or
if (!$bar) // ...
}
With a Not operator it's more compact, but you may not notice this operator while reading a code.
And why do some coders write in Yoda style like false === $bar ?
The obvious reason is in case you don't have Boolean return value and need to differentiate between other falsy values (0, false, null, "0", etc). For example when using
strrpos()you might getfalsewhich is different than0.As for the ugly Yoda style, that is to avoid mistakes such as
$bar = falseinstead of$bar == false. You would get error if you triedfalse = $barand notice it straight away.