PHP 条件赋值
PHP conditional assignment
在 Symfony 核心中发现一段有趣的代码
if ('' !== $host = $route->getHost()) {
...
}
!== 的优先级比= 高,但是它是如何逻辑工作的呢?第一部分清楚了,剩下的呢?
我创建了一个小示例,但仍然不清楚:sample
关键是:赋值的左边必须是一个变量!在您的示例中实现此目的的唯一可能方法是首先评估分配 - 这就是 php 实际所做的。
添加括号说明会发生什么
'' !== $host = $route->getHost()
// is equal to
'' !== ($host = $route->getHost())
// the other way wouldn't work
// ('' != $host) = $route->getHost()
所以条件为真,如果 $route->getHost()
的 return 值是非空字符串,并且在每种情况下,return 值都分配给 $host
.
此外,您可以查看 PHP
的 grammer
...
variable '=' expr |
variable '=' '&' variable |
variable '=' '&' T_NEW class_name_reference | ...
如果您仔细阅读运营商 precendence manual 页面,您会看到此通知
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.
在 Symfony 核心中发现一段有趣的代码
if ('' !== $host = $route->getHost()) {
...
}
!== 的优先级比= 高,但是它是如何逻辑工作的呢?第一部分清楚了,剩下的呢?
我创建了一个小示例,但仍然不清楚:sample
关键是:赋值的左边必须是一个变量!在您的示例中实现此目的的唯一可能方法是首先评估分配 - 这就是 php 实际所做的。
添加括号说明会发生什么
'' !== $host = $route->getHost()
// is equal to
'' !== ($host = $route->getHost())
// the other way wouldn't work
// ('' != $host) = $route->getHost()
所以条件为真,如果 $route->getHost()
的 return 值是非空字符串,并且在每种情况下,return 值都分配给 $host
.
此外,您可以查看 PHP
的 grammer...
variable '=' expr |
variable '=' '&' variable |
variable '=' '&' T_NEW class_name_reference | ...
如果您仔细阅读运营商 precendence manual 页面,您会看到此通知
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.