加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 从函数返回“错误”的最佳做法

发布时间:2020-12-13 14:02:24 所属栏目:PHP教程 来源:网络整理
导读:我有一个功能: public function CustomerRating() { $result = $db-query("..."); $row = $result-fetch_assoc(); if($row) $output = $row['somefield']; } else { $output = "error"; } return $output;}//somewhere on another page...if(is_numeric($cl
我有一个功能:
public function CustomerRating() {
     $result = $db->query("...");
     $row = $result->fetch_assoc();

     if($row)
          $output = $row['somefield'];
     } else {
          $output = "error";
     }

     return $output;
}

//somewhere on another page...
if(is_numeric($class->CustomerRating()) {
     echo $class->CustomerRating;
} else {
      echo "There is an error with this rating.";
}

有没有更好的方法来发现错误?在这个函数中,如果没有返回任何行,它本身并不意味着“错误”,它只是意味着无法计算该值.当我检查一个函数的结果时,我觉得有一个更好的方法来检查在if函数中显示之前返回的数据.最好的方式是做什么?我想返回一个“false”,但是当调用这个函数时我该怎么检查呢?谢谢!

有(在我看来)有两种常见的方法:

>返回错误
许多内置的PHP函数做到这一点
>使用SPL exceptions演进的PHP框架(Symfony2,ZF2,…)这样做

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读