dongmaoxi0477 2014-02-20 12:16
浏览 149
已采纳

PDO :: FETCH_OBJ +自定义类?

When I fetchAll() query results (SELECT * FROM users ...) as an array of objects, I want these objects to be of a certain class, namely User.

  1. How do I force PDO to use the data type User for the result objects, and
  2. do I have to define all member variables corresponding to the field names in the class?
  • 写回答

2条回答 默认 最新

  • duanouyong4228 2014-02-20 12:24
    关注

    there is a static field to tell PDO to fetch into a class, PDO::FETCH_CLASS.

    Here is an example of getting User objects;

    class User {
        public $name;
        public $firstname;
    }
    

    You have to ensure that the field names are same as the column ones and that the class is accessible from the class / file you're working from. (SELECT * works too, just have all fields available)

    $query = "SELECT name, firstname FROM users";
    

    And to wrap it in classes, use the next,

    $users = $sth->fetchAll(PDO::FETCH_CLASS, "User");
    

    Then you can simply access it as an array of User objects.

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效