如何让PHP避免懒惰求值? [英] How can I have PHP avoid lazy evaluation?
问题描述
关于PHP评估布尔表达式的方式,我有一个有趣的问题.例如,如果有,
I have an interesting question about the way PHP evaluates boolean expressions. When you have, for example,
$expression = $expression1 and $expression2;
或
if ($expression1 and $expression2)
PHP首先检查$expression1
的评估结果是否为 true
.如果不是这种情况,那么只需跳过$expression2
即可避免不必要的计算.在我编写的脚本中,我有:
PHP first checks if $expression1
evaluates to true
. If this is not the case, then $expression2
is simply skipped to avoid unnecessary calculations. In a script I am writing, I have:
if ($validator->valid("title") and $validator->valid("text"))
我需要对第二条语句($validator->valid("text")
)进行评估,即使第一条语句的评估结果为false.我想问你,是否有一些简单的方法可以强制PHP始终评估这两个语句.谢谢!
I need to have the second statement ($validator->valid("text")
) evaluated even if the first one evaluates to false. I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!
推荐答案
这称为短路评估,为避免这种情况,您需要使用单个&
:
This is known as short circuit evaluation, and to avoid it you need to do this, using a single &
:
if($validator->valid("title") & $validator->valid("text")) {
}
请注意,这不是使用逻辑运算符,而是实际上是
Note that this is not using logical operators but actually bitwise operators:
它们是对数字的二进制表示起作用的运算符.在不先将逻辑值分别转换为数字1和0的情况下,它们不会将逻辑值(即"true"或"false")作为参数.它们也不返回逻辑值,而是数字.当然,您以后可以将这些数字视为逻辑值(在这种情况下,0强制转换为"false",其他所有强制转换为"true"),但这是PHP的类型强制转换规则的结果,无需执行任何操作与操作员的行为有关.
They're operators that act on the binary representations of numbers. They do not take logical values (i.e., "true" or "false") as arguments without first converting them to the numbers 1 and 0 respectively. Nor do they return logical values, but numbers. Sure, you can later treat those numbers as though they were logical values (in which case 0 is cast to "false" and anything else is cast to "true"), but that's a consequence of PHP's type casting rules, and nothing to do with the behavior of the operators.
因此,关于使用这种副作用规避短路评估是否是一种好习惯,存在一些争议.我个人至少要评论一下&是有意的,但是如果您想变得尽可能纯正,则应该先评估它们是否有效,然后再执行if.
As such, there is some debate as to whether it is good practice to use this side effect to circumvent short-circuit evaluation. I would personally at least put a comment that the & is intentional, but if you want to be as pure as possible you should evaluate whether they are valid first and then do the if.
这篇关于如何让PHP避免懒惰求值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!