本文介绍了如何让PHP避免懒惰求值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于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:

因此,关于使用这种副作用规避短路评估是否是一种好习惯,存在一些争议.我个人至少要评论一下&是有意的,但是如果您想变得尽可能纯正,则应该先评估它们是否有效,然后再执行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避免懒惰求值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:28
查看更多