What's the meaning of the reverse entry (null

2020-04-07 20:05发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
PHP - reversed order in if statement
Checking for null - what order?

Examining Zend Framework found that they do all the variable checkings reverse way:

public function setBootstrap($path, $class = null) {

   if (null === $class) {    // instead of if($class === null)
      $class = 'Bootstrap';
   }

What's the reason of doing this?

Is this also suitable for Java and C++ programming?

回答1:

some people believe it helps them in avoiding to write a single = (an assignment instead of a comparison for equality)

I believe that the advantage of doing so is much less than the loss of readability (and therefore maintainability!)

People who don't test their code may rely on this sort of trick. And to answer your question, yes, it is suitable for most languages who derive their syntax from C - I mean suitable, not recommended.



回答2:

This style is called yoda conditions.

Basically it has the same behavior as the usual ( $variable === value ) style, but with one advantage:

The compiler throws an error in case you write = instead of == or === by mistake. As you can't reassign a constant (in the example the null value), the developer immediately recognizes the mistake due to a compiler error/warning and thus is relieved of a time consuming bug search.

So the following line would be valid, although it wont show the (most of the time) intended behavior:

if ( $var = null ) { echo 'test'; }

While here an error is shown:

if ( null = $var ) { echo 'test'; }

A major drawback, however, is the loss of readability with this style. But this depends on the reader of the code and some other coding style guidelines.



回答3:

This is a yoda condition, I dont know about any benefits except you cant assign the value to the variable when you accidentally write for example

if( $foo = "bar" )


Here a Link for more examples:

http://united-coders.com/christian-harms/what-are-yoda-conditions



回答4:

In this case comparison takes in account value and a type of the value. this is a strict comparison.

For example this code:

if (null == "") {
  echo "null";
}

Will print "null" as far as PHP treats "", 0, null, false as equivalent empty values unless strict comparison is used to compare actual value and type of the value itself.

Second thing is why null === $class is used is because you can not assign value to null. Whereas you can successfully make mistake and assign $class = null.