问题描述
先举个简单的例子:
函数 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函数返回值,如何检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!