views:

49

answers:

2

Often I stumble upon following approach of defining conditional statement:

if(false === $expr) {
       ...
}

I have several questions about this.

  1. Is there a point of using constant value (false, 1, 0, 123, 'string' etc) as a first operand instead of second in cases when second operand is not too long. For example, I would prefer to put false as the first operand when I have following statement:

    if(false === file_put_contents($file_path, $document['title'].PHP_EOL.PHP_EOL.$document['body'])) { ... }

  2. Does it make sense at all to use such approach in interpreted language which php is? I assume this comes from compiled languages such as Java when we want to avoid NullPointerException or in similar cases. Am I right?

  3. What useful cases of using constant value as first operand do you know?

+3  A: 

Actually this comes from a quick-typer mistake like this in C:

 if( lenght = 0 ) { ... }

Where variables were unintentionally set to the compared value. Reversing the intended comparison would generate a compiler error.

xtofl
+1 I would have posted the same :)
Mahesh Velaga
I find it ironic that in what you already refer to as a "quick-typer mistake", there is a typo ("lenght" instead of "length"). :P
Amber
A: 

Strict comparison - AFAIK - is useful when you use functions that would return 0 as a possible result and boolean case in case of errors. See for example the strpos() function.

As for using a constant as a first parameter, I prefer that in order to get an error in case I mistakenly assign a value rather than doing a comparison. Es: $value = false will be accepted false = $value will trigger an error.

HTH

mac