dongtiao2976 2009-04-02 10:09
浏览 43
已采纳

我如何让PHP避免懒惰评估?

I have an interesting question about the way PHP evaluates boolean expressions. When you have, for example,

$expression = $expression1 and $expression2;

or

if ($expression1 and $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"))

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!

  • 写回答

6条回答 默认 最新

  • doupingyun73833 2009-04-02 10:13
    关注

    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:

    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.

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部