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

报告相同问题?