PHP Conditional Assignment

Found an interesting piece of code in the core of Symfony

if ('' !== $host = $route->getHost()) { ... } 

Priority! == is higher than =, but how does it work logically? The first part is clear, but the rest?

I created a small sample, but it is still not clear: the sample

+6
source share
1 answer

Point: the left side of the job must be variable! The only possible way to achieve this in your example is to first evaluate the purpose, which is what php does.

Adding brackets makes it clear what is going on

 '' !== $host = $route->getHost() // is equal to '' !== ($host = $route->getHost()) // the other way wouldn't work // ('' != $host) = $route->getHost() 

So, the condition is true if the return value of $route->getHost() is an empty string and in each case the return value is assigned to $host .

Alternatively, you can look at the PHP grammer

 ... variable '=' expr | variable '=' '&' variable | variable '=' '&' T_NEW class_name_reference | ... 

If you carefully read the preview guide page, you will see this notification

Although = has a lower priority than most other operators, PHP will still allow expressions like the following: if (! $ A = foo ()), in which case the return value of foo () is placed in $ a.

+3
source

Source: https://habr.com/ru/post/1015529/


All Articles