PHP 条件赋值 [英] PHP conditional assignment

查看:41
本文介绍了PHP 条件赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Symfony 核心中发现一段有趣的代码

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

!== 的优先级高于 = 但它在逻辑上是如何工作的?第一部分很清楚,但其余部分?

我已经创建了一个小示例,但仍然不清楚:示例

解决方案

重点是:赋值的左边必须是一个变量!在您的示例中实现这一点的唯一可能方法是首先评估分配 - 这就是 php 实际所做的.

添加括号清楚,会发生什么

'' !== $host = $route->getHost()//等于'' !== ($host = $route->getHost())//其他方式行不通//('' != $host) = $route->getHost()

所以条件为真,如果 $route->getHost() 的返回值是一个非空字符串,并且在每种情况下,返回值都分配给 $host.

另外,你可以看看语法 PHP

<预><代码>...变量 '=' expr |变量 '=' '&'变量 |变量 '=' '&'T_NEW class_name_reference |...

如果您仔细阅读操作员优先手册页面,您会看到这个通知

<块引用>

尽管 = 的优先级低于大多数其他运算符,但 PHP 将仍然允许类似于以下的表达式:if (!$a = foo()), in这种情况下 foo() 的返回值放入 $a 中.

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

解决方案

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.

这篇关于PHP 条件赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆