当前位置:Gxlcms > PHP教程 > 问个PHP代码规范的问题

问个PHP代码规范的问题

时间:2021-07-01 10:21:17 帮助过:11人阅读

首先,有个函数是这么写的。

  1. <code>function exam(){
  2. //从数据库获取数据。
  3. $records = $aModel->where(['type' => 1])->get();
  4. if(empty($records)) return false;
  5. $newRecord = $bModel->map();
  6. foreach($records as $item){
  7. $newRecord->name = $item->name;
  8. $newRecord->age = $item->age;
  9. try{
  10. $bModel->insert($newRecord);
  11. }
  12. catch(\Exception $e){
  13. \Log::catch($e);
  14. }
  15. }
  16. return true;
  17. }
  18. </code>

然后,这个函数是这么调用的。

  1. <code>if(true !== exam()){
  2. echo "表更新失败";
  3. return false;
  4. }</code>

请各位经验丰富的phper看下,这其中有几个地方看着挺别扭的:

  1. 函数exam()中,return 的位置是否合适。

  2. 假如遇到函数中返回类型不确定,执行完成返回结果,执行失败返回false这种情况下,调用的时候是否适合对结果进行类似 if(false === exam()) 的判断。

  3. 感觉在if判断中执行函数,会使得代码的可读性降低,不知是否存在这样的问题。

回复内容:

首先,有个函数是这么写的。

  1. <code>function exam(){
  2. //从数据库获取数据。
  3. $records = $aModel->where(['type' => 1])->get();
  4. if(empty($records)) return false;
  5. $newRecord = $bModel->map();
  6. foreach($records as $item){
  7. $newRecord->name = $item->name;
  8. $newRecord->age = $item->age;
  9. try{
  10. $bModel->insert($newRecord);
  11. }
  12. catch(\Exception $e){
  13. \Log::catch($e);
  14. }
  15. }
  16. return true;
  17. }
  18. </code>

然后,这个函数是这么调用的。

  1. <code>if(true !== exam()){
  2. echo "表更新失败";
  3. return false;
  4. }</code>

请各位经验丰富的phper看下,这其中有几个地方看着挺别扭的:

  1. 函数exam()中,return 的位置是否合适。

  2. 假如遇到函数中返回类型不确定,执行完成返回结果,执行失败返回false这种情况下,调用的时候是否适合对结果进行类似 if(false === exam()) 的判断。

  3. 感觉在if判断中执行函数,会使得代码的可读性降低,不知是否存在这样的问题。

  1. exam()中的return 为什么不在抛出异常的时候就直接return false?

  2. 一般返回类型如果是bool类型不建议加第三种类型,你说的那种方法可以判断但是不建议

  3. 可读性的问题不是因为在if里,而是你的函数名有问题,如果要返回是bool型建议加个is来表示, 如:

  1. <code class="php">if(false === isExam()){
  2. echo "表更新失败";
  3. return false;
  4. }</code>

推荐一本书你可以看看:
https://book.douban.com/subje...

人气教程排行