While scrolling through code you might come across something like this if (1 === $var).
What could possibly be the difference between if ($var === 1) and if (1 === $var) ?
It has to be known that there is no difference in functionality between the two approaches. So, why the hell would you use a Yoda condition when writing conditions ?
When writing an if statement, it may have happened that you missed some equal signs. The problem is when you end up with something like this:
if ($var = 1) { // Instead of $var === 1 // Do something }
What happens here ?
No error is detected because this is code is valid. The problem is that it does not work like intended: the variable is assigned to the value 1, no comparison is performed and it is always true.
This is where the Yoda condition is useful; with the same case, we get:
if (1 = $var) { // Instead of 1 === $var // Do something }
Here we also missed some equals but the code is not valid and, this time, we get an error since this is not valid.
We have seen that the sole purpose of the Yoda condition is to avoid accidental assignment which comes at the cost of less readeability.
Should you use it ? Why not ! But keep in mind that this will not improve your code by any margin.
Also it can help to flex at a party with devs (which does not occur that often by the way).
For you reading, thank you ! ?
The above is the detailed content of Yoda condition, in PHP, What is ?. For more information, please follow other related articles on the PHP Chinese website!