简体   繁体   English

PDO :: FETCH_OBJ +自定义类?

[英]PDO::FETCH_OBJ + custom classes?

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 . 当我将fetchAll()查询结果( SELECT * FROM users ... )作为对象数组时,我希望这些对象属于某个类,即User

  1. How do I force PDO to use the data type User for the result objects, and 如何强制PDO将结果对象的数据类型User用于,和
  2. do I have to define all member variables corresponding to the field names in the class? 我是否必须定义与类中的字段名称对应的所有成员变量?

there is a static field to tell PDO to fetch into a class, PDO::FETCH_CLASS . 有一个静态字段告诉PDO获取类PDO::FETCH_CLASS

Here is an example of getting User objects; 以下是获取User对象的示例;

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) SELECT *适用,只有所有字段可用)

$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. 然后,您只需将其作为User对象数组进行访问即可。

Have a look at http://www.php.net/manual/en/pdostatement.setfetchmode.php Setting the fetch mode to FETCH_CLASS should get you on your way. 看看http://www.php.net/manual/en/pdostatement.setfetchmode.php将获取模式设置为FETCH_CLASS应该可以帮助您。

Edit: KarelG beat me to it ;) 编辑:KarelG打败了我;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM