php函数return两个值

php function return two values

为什么在 if 语句中和 if 语句外部都有一个 return 语句。有人可以解释为什么这样做吗?

 public function fetch_countries($limit, $start) {
            $this->db->limit($limit, $start);
            $query = $this->db->get("Country");

            if ($query->num_rows() > 0) {
                foreach ($query->result() as $row) {
                    $data[] = $row;
                }
                **return $data;**
            }
            **return false;**
       }

为什么不这样写

public function fetch_countries($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->get("Country");

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            **return $data;**
        }else{
            **return false;**
        }

   }

两个代码块将 运行 以完全相同的方式进行,第一个代码块更优雅一些。

在第一个示例中,如果 ($query->num_rows() > 0) 的计算结果为真,则函数将始终执行return $data,因为它在 if 语句的代码块中,这意味着在函数中的那行代码之后将不会执行任何内容。所以在这种情况下,它永远不会到达 if 语句之外的 return false,因此在第二个示例中有 else 是不必要的。