問(wèn)題描述
有什么辦法可以將 PDO 的結(jié)果作為構(gòu)造函數(shù)的參數(shù)傳遞?假設(shè)我有以下課程:
Is there any way, to pass results of PDO as parameters of the constructor? Let's say, I have the following class:
class Test
{
private $value1;
private $value2;
function __construct($val1, $val2)
{
$this->value1 = $val1; $this->value2 = $val2;
}
}
然后,通過(guò) PDO 驅(qū)動(dòng)程序,我從數(shù)據(jù)庫(kù)中選擇一些數(shù)據(jù),讓我們說(shuō):
Then, via PDO driver I select some data from DB, let's say:
SELECT price, quantity FROM stock
$results = $query->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, "Test");
現(xiàn)在,PDO 將這些值直接傳遞給類字段,并繞過(guò)構(gòu)造函數(shù).
Right now, PDO passess these values directly to the class fields, and bypassing the constructor.
也許我遺漏了一些東西,但我想將查詢的結(jié)果傳遞給構(gòu)造函數(shù).構(gòu)造函數(shù)不能依賴于查詢,我希望即使不使用 PDO 也能實(shí)例化這個(gè)類.
Maybe I am missing something, but I want to pass results from the query to the constructor. Constructor cannot be query-dependent, I want to be able to instantiate this class even without using PDO.
推薦答案
[我編輯了這個(gè)答案,因?yàn)槲抑暗拇鸢覆辉贉?zhǔn)確.]
[I edited this answer as my previous answer is not accurate anymore.]
FETCH_CLASS 確實(shí)會(huì)獲取私有屬性.請(qǐng)參考這個(gè)答案.
FETCH_CLASS does fetch into private properties. Please refer to this answer.
這篇關(guān)于PDO - FETCH_CLASS - 將結(jié)果作為參數(shù)傳遞給構(gòu)造函數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!