在下面的php函数中,我在失败时返回一条错误消息。我也必须返回false吗?因为我会像下面的代码那样使用函数。
function addThis($a) {
global $msg;
if($a == 1) {
return true;
} else {
$msg = 'Error';
//return false; -> Should I compulsorily be using return false here
}
}
上述函数的用法
如果为false,则正常工作并显示错误消息。但是,由于没有从函数返回false,是否有可能出现问题?我应该强制在函数内使用return false吗?
if (addThis(12)) {
echo 'Cool';
} else {
echo $msg;
}
没有它也可以工作,但添加它不会有什么坏处,而且肯定会被认为是更好的风格,因为它使您的意图清晰,并且意味着函数始终返回布尔值。
没有它的原因是,如果PHP到达一个函数的末尾而没有碰到return
语句(或者如果你说return;
没有值),该函数被认为返回null
。当您随后在if
语句中测试该值时,它被转换为布尔值,并被视为false
,从而到达else
子句。
但是由于false没有从函数返回,是否有可能出现问题?
不,它不会,只要函数定义与您在问题中显示的相同。由于else
部分之后没有其他内容,因此在本例中不会出错。
然而,最好的做法是从函数中取出return
,然后在条件中使用它。
实际上你提供的代码似乎没有问题;因为PHP思想开阔,不介意这些可忽略的技术细节。但Boolean Function
到return
至少是True/False in any condition
的best practice
。
这样函数将执行两个方面;
first: will show a message "Error" second: will return false (behind the screen) function-wise; and will eradicate the error possibility with other functions
function addThis($a) {
global $msg;
if($a == 1) {
return true;
} else {
$msg = 'Error';
return false; // Yes, recommended that you should use "return false;" here
// Without "return false;" it can create problems when using with other functions
// BUT IT IS NOT COMPULSORY
}
}