PHP 有短路评估吗? [英] Does PHP have short-circuit evaluation?

查看:32
本文介绍了PHP 有短路评估吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

if (is_valid($string) && up_to_length($string) && file_exists($file)) 
{
    ......
}

如果is_valid($string)返回false,php解释器是否还会检查后面的条件,比如up_to_length($string)?
如果是这样,那么为什么它在不需要的时候做额外的工作?

If is_valid($string) returns false, does the php interpreter still check later conditions, like up_to_length($string)?
If so, then why does it do extra work when it doesn't have to?

推荐答案

是的,PHP 解释器是懒惰的",这意味着它会进行尽可能少的比较来评估条件.

Yes, the PHP interpreter is "lazy", meaning it will do the minimum number of comparisons possible to evaluate conditions.

如果你想验证,试试这个:

If you want to verify that, try this:

function saySomething()
{
    echo 'hi!';
    return true;
}

if (false && saySomething())
{
    echo 'statement evaluated to true';
}

这篇关于PHP 有短路评估吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆