【问题标题】:Return an empty but tell php it means `return false`返回一个空但告诉 php 这意味着 `return false`
【发布时间】:2015-08-03 09:36:19
【问题描述】:

是否可以返回一个数组,同时告诉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 取一个数组,对吧?

【问题讨论】:

  • 返回一个空数组..
  • 这可能是因为 PHP 不是强类型的?您可以测试输入是否为 Abra 提到的“true”或“is_array”

标签: php arrays return


【解决方案1】:

方法很多。可能是首选,与带有类型检查的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
}

【讨论】:

    【解决方案2】:

    我会用 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 变量中的内容。我写了一篇小文章解释了为什么mixed-typed return values 会如此危险。

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多