First of all, there is a function written like this.
<code>function exam(){ //从数据库获取数据。 $records = $aModel->where(['type' => 1])->get(); if(empty($records)) return false; $newRecord = $bModel->map(); foreach($records as $item){ $newRecord->name = $item->name; $newRecord->age = $item->age; try{ $bModel->insert($newRecord); } catch(\Exception $e){ \Log::catch($e); } } return true; } </code>
Then, this function is called like this.
<code>if(true !== exam()){ echo "表更新失败"; return false; }</code>
Experienced PHPers please take a look, there are a few places that look quite awkward:
In the function exam(), is the position of return appropriate?
If the return type of a function is uncertain, the result will be returned if the execution is completed, and false will be returned if the execution fails. In this case, is it appropriate to judge the result similar to if(false === exam())
when calling.
I feel that executing functions in if judgments will reduce the readability of the code. I wonder if such a problem exists.
First of all, there is a function written like this.
<code>function exam(){ //从数据库获取数据。 $records = $aModel->where(['type' => 1])->get(); if(empty($records)) return false; $newRecord = $bModel->map(); foreach($records as $item){ $newRecord->name = $item->name; $newRecord->age = $item->age; try{ $bModel->insert($newRecord); } catch(\Exception $e){ \Log::catch($e); } } return true; } </code>
Then, this function is called like this.
<code>if(true !== exam()){ echo "表更新失败"; return false; }</code>
Experienced phpers please take a look, there are a few places that look quite awkward:
In the function exam(), is the position of return appropriate?
If the return type in the function is uncertain, the result will be returned if the execution is completed, and false will be returned if the execution fails. In this case, is it appropriate to judge the result similar to if(false === exam())
when calling.
I feel that executing functions in if judgments will reduce the readability of the code. I wonder if such a problem exists.
Why not just return false when an exception is thrown?
If the general return type is bool type, it is not recommended to add a third type. The method you mentioned can be used to judge but it is not recommended
The problem with readability is not because it is in the if, but because there is a problem with your function name. If you want to return a bool type, it is recommended to add an is to express it, such as:
<code class="php">if(false === isExam()){ echo "表更新失败"; return false; }</code>
Recommend a book you can read:
https://book.douban.com/subje...