是否有可能返回一个数组,但也告诉php它应该意味着false?
的例子:
if ($res = a_function()) {
// all good
}
else {
echo getErrorByNumber($res['err_no']);
}
a_function
:
function a_function() {
// do fancy stuff
if (xy) return true;
return array('err_no' => 1);
}
我想这是不可能的,因为php将始终采取数组return true
,对吧?
方法很多。可能是首选,比较true
与类型检查===
:
if(($res = a_function()) === true) {
// all good
}
else {
echo getErrorByNumber($res['err_no']);
}
非空数组将始终为真:
if($res = a_function() && !is_array($res)) {
// all good
}
else {
echo getErrorByNumber($res['err_no']);
}
或者反过来看:
if(is_array($res)) { //or isset($res['err_no'])
echo getErrorByNumber($res['err_no']);
}
else {
// all good
}
我可以用一个byref参数来解决这个问题:
function foo(&$errors)
{
if (allWentWell())
{
$errors = null;
return true;
}
else
{
$errors = array('err_no' => 007);
return false;
}
}
// call the function
if (foo($errors))
{
}
else
{
echo getErrorByNumber($errors['err_no']);
}
这样,您就不必区分不同可能的返回类型,也不会遇到类型杂耍问题。它也更可读,你知道$errors变量里面有什么,没有文档。我写了一篇小文章来解释为什么混合类型的返回值如此危险。