doulipi3742 2017-05-18 11: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 11: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条)

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写