php - Logical operators should be avoided (use || instead of 'or') sensiolabs insight
I'm using SensioLabs Insight to keep my projects code quality on top of the used tool's best practices.
This line cause warning during SLInsight analysis:
$handle = fopen($file, 'w') or die('Cannot open file: '.$file);
SensioLabs say :
Logical operators should be avoided.
[...]
The or operator does not have the same precedence as ||. This could lead to unexpected behavior, use || instead.
Ok but, if I simply use || instead of 'or' , like this :
$handle = fopen($file, 'w') || die('Cannot open file: '.$file);
I get the classicNo such file or directory
erro because offopen
fail,
instead of what I'm expecting (die action and return message).
To avoid this, I use a condition before do thefopen
:
if(!file_exists($file)) {
throw $this->createNotFoundException('Le fichier '.$file.' n\'existe pas.');
}
$handle = fopen($file'.log', 'r');
What is the good use of '||' in a variable assignment for what I want ?
Thank's by advance for enlighten me.
Answer
Solution:
In your case is the precedence of the
or
that you want. I think that SensioLabs refers to a complex expressions in a condition, which can be misleading.or
operator have lower precedence, even lower than assignment=
operator. Example:is as you would expect:
$a
contains the value returnedgetRecordOrFalse
, and this condition istrue
if$boolValue
is true, even if$a
isn't. But with theor
you get a completely different behavior:that's equivalent to:
Now
$a
would be a boolean value given by the result ofgetRecordOrFalse($userId) or $boolValue)
's condition.But in your case this make sense:
What you can do to improve readability is to use a condition like this:
Or simply