Heim  >  Artikel  >  Backend-Entwicklung  >  问个PHP代码规范的问题

问个PHP代码规范的问题

WBOY
WBOYOriginal
2016-10-11 14:23:381066Durchsuche

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

<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>

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

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

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

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

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

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

回复内容:

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

<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>

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

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

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

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

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

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

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

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

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

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

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn