gpt4 book ai didi

PHP 条件赋值

转载 作者:可可西里 更新时间:2023-11-01 12:57:20 33 4
gpt4 key购买 nike

在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() 的返回值是一个非空字符串,并且在每种情况下,返回值都分配给 $host.

此外,您可以查看 grammer PHP的

...
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.

关于PHP 条件赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42629076/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com