Return 一个空但告诉 php 它意味着 `return false`

Return an empty but tell php it means `return false`

是否可以 return 一个数组,同时告诉 php 它应该表示错误?

示例:

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']);
}

这样您就不必区分可能的 return 类型,也不会 运行 陷入类型杂耍问题。它也更具可读性,您知道 $errors 变量中的内容而无需文档。我写了一篇小文章来解释为什么 mixed-typed return values 会如此危险。