PHP函数返回值,如何检查 [英] PHP function return value, how to check

查看:61
本文介绍了PHP函数返回值,如何检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先举个简单的例子:

函数 doReturnSomething(){//一些逻辑如果($resultFromLogic){返回 Default_Model_Something;}返回假;}

如您所见,此函数返回一个模型或 false.现在,让我们从其他地方调用这个函数:

$something = doReturnSomething();

不,我想放置一个 if 语句来检查变量 $something.让我们说:

if (false !== $something) {}

if ($something instanceof Default_Model_Something) {}

<预><代码>...

对于这种情况,是否有最佳实践"?检查错误或使用实例.这种特殊方式有什么后果吗?

提前致谢!

解决方案

我认为从 PHP 5.4 开始有一个特殊的警告错误,用于威胁逻辑语句中的函数返回.

好的做法是将函数的结果保存到变量中,然后在任何逻辑语句中使用它.

First a simple example:

function doReturnSomething()
{
    // some logic
    if ($resultFromLogic) {
        return Default_Model_Something;
    }

    return false;
}

As you can see, this functions returns a model or false. Now, let's call this function from some place else:

$something = doReturnSomething();

No, I want to put a if-statement to check the variable $something. Let's say:

if (false !== $something) {}

or

if ($something instanceof Default_Model_Something) {}

or

...

Is there a "best practice" for this situation to do? Check for false or use instance of. And are there any consequences for that particular way?

Thank is advance!

解决方案

I think that from PHP 5.4 on there is a special notice error for threating a function return in logical statements.

Good pratice is to save result of a function to variable and then use it in any logical statement.

这篇关于PHP函数返回值,如何检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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