PHP conditional assignment

元气小坏坏 提交于 2021-02-07 13:14:17

问题


Found an interesting piece of code in Symfony core

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

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

I've created a little sample but it's still not clear: sample


回答1:


The point is: The left hand side of an assignment has to be an variable! The only possible way to achieve this in your example is to evaluate the assignment first - which is what php actually does.

Adding parenthesis makes clear, what happens

'' !== $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 non empty string and in each case, the return value is assigned to $host.

In addition, you could have a look a the grammer of PHP

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

If you read the operator precendence manual page carefully, you would see this notice

Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.



来源:https://stackoverflow.com/questions/42629076/php-conditional-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!