doulipi3742 2017-05-18 03:15
浏览 218
已采纳

返回数据库对象的PHP方法的返回类型?

What return type I should replace in "WHAT?" text. And if the query returns no results?

I'm using PHP 7.1

The method is:

public function retrieveSomething(int $id_user): WHAT? {
    try {
        $this->sql = 'SELECT * FROM tbl_users WHERE IdUser = :id_user';
        $stmt = $this->db->prepare($this->sql);
        $stmt->bindValue(':id_user', $id_user, PDO::PARAM_INT);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_OBJ);
        $stmt->closeCursor();
        return $row;
    } catch (PDOException $e) {
        throw $e;
    } catch (Exception $e) {
        throw $e;
    }
}
  • 写回答

3条回答 默认 最新

  • dongyongyu0789 2017-05-18 03:21
    关注

    From manual:

    PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set

    You have some examples among the user comments:

    object(stdClass)#6 (3) {
      ["1"]=>
      string(1) "1"
      ["2"]=>
      string(1) "2"
      ["3"]=>
      string(1) "3"
    }
    

    So:

    public function retrieveSomething(int $id_user): \stdClass {
    }
    

    ... should work (I don't have PHP/7 here to test).

    Also:

    The return value of this function on success depends on the fetch type. In all cases, FALSE is returned on failure.

    To avoid this, you should configure PDO to throw exceptions (which you apparently already did, and is a good idea by itself).

    Additionally, I suggest you drop the try/catch blocks, they're completely redundant.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部