问题描述
我试图弄清楚如何从PDO获取到我的自定义类,以及通常从PDO到对象的API,并且发现缺乏体面的文档令人沮丧.大多数选项仅作为选项记录,而所有示例都使用提取到数组中.
因此,有人可以解释如何使用它们:
I am trying to figure out how to fetch from PDO into my custom class, and in general the PDO-to-object API, and am finding the lack of decent documentation frustrating. Most of the options are only documented as an option, while the examples all use fetching into arrays.
So, can someone explain how these are used:
- PDO :: FETCH_OBJ
- PDO :: FETCH_CLASS
- PDO :: FETCH_CLASSTYPE
- PDO :: FETCH_INTO
- PDO :: FETCH_LAZY
- PDOStatement :: fetch
- PDOStatement :: fetchObject
- PDOStatement :: setFetchMode
如果可能的话,我想对如何使用每个函数/常量来获取对象进行一般性解释,或者有什么区别,以及如何获取类的具体答案,例如进入:
If possible, I would like a general explanation how each function/constant is used for fetching objects, or what the differences are, as well as a specific answer to how do I fetch into my class, e.g. into:
class MyRow {
public $col1, $col2;
}
推荐答案
这是我设法弄清的东西:
Here is what I managed to figure out:
-
PDO :: FETCH_OBJ
用于获取未命名(匿名")对象的新实例
PDO::FETCH_OBJ
Is used to fetch into a new instance of an unnamed ("anonymous") object
PDO :: FETCH_CLASS
用于获取现有类的新实例(列名称应与现有属性匹配,或者应使用__set
接受所有属性).设置属性后,将调用该类的构造函数.
PDO::FETCH_CLASS
Is used to fetch into a new instance of an existing class (the column names should match existing properties, or __set
should be used to accept all properties). The constructor of the class will be called after the properties are set.
PDO :: FETCH_CLASSTYPE
与FETCH_CLASS
(按位或)一起使用时,用于创建的实例的类的名称位于第一列中,而不是提供给函数.
PDO::FETCH_CLASSTYPE
Used with FETCH_CLASS
(bitwise OR), the name of the class to create an instance of is in the first column, instead of supplied to the function.
PDO :: FETCH_INTO
与FETCH_CLASS
使用相同类型的类(必须将所有列作为属性名称处理),但是更新现有对象而不是创建新对象.
PDO::FETCH_INTO
Is used with the same type of class as FETCH_CLASS
(must handle all columns as property names), but updates an existing object as opposed to creating a new one.
PDO :: FETCH_LAZY
我不知道这是怎么回事.
PDO::FETCH_LAZY
I don't know what this does.
-
PDOStatement :: fetch
常规的get-a-row命令.我不知道如何在FETCH_CLASS
或FETCH_INTO
中使用它,因为没有任何方法可以传递类名/实例.
PDOStatement::fetch
The regular get-a-row command. I don't know how to use this withFETCH_CLASS
orFETCH_INTO
since there does not be any way to pass the class name/instance.
PDOStatement :: fetchObject
一种执行FETCH_CLASS
或FETCH_INTO
的方法,包括传递构造函数args.没有参数是FETCH_OBJ
的简写.
PDOStatement::fetchObject
A way to do FETCH_CLASS
or FETCH_INTO
, including passing constructor args. With no args is a shorthand for FETCH_OBJ
.
PDOStatement :: setFetchMode
设置默认提取模式的一种方法,以便可以在不使用args的情况下调用PDOStatment::fetch
.
PDOStatement::setFetchMode
A way to set the default fetch mode, so that PDOStatment::fetch
can be called without args.
那是我设法弄清楚的最好的.我希望它可以帮助其他人(我需要fetchObject
方法)
That is the best I managed to figure out. I hope it helps someone else (I needed the fetchObject
method)
这篇关于PHP PDO获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!