問題描述
我有一個使用魔法方法來存儲屬性的類.這是一個簡化的例子:
I have a class that uses magic methods to store properties. Here is a simplified example:
class Foo {
protected $props;
public function __construct(array $props = array()) {
$this->props = $props;
}
public function __get($prop) {
return $this->props[$prop];
}
public function __set($prop, $val) {
$this->props[$prop] = $val;
}
}
我試圖在執行后為 PDOStatement
的每個數據庫行實例化此類的對象,如下所示(不起作用):
I'm trying to instantiate objects of this class for each database row of a PDOStatement
after it's executed, like this (doesn't work):
$st->setFetchMode(PDO::FETCH_CLASS, 'Foo');
foreach ($st as $row) {
var_dump($row);
}
問題是 PDO::FETCH_CLASS
在我的類上設置屬性值時似乎沒有觸發神奇的 __set()
方法.
The problem is that PDO::FETCH_CLASS
does not seem to trigger the magic __set()
method on my class when it's setting property values.
如何使用 PDO 實現預期效果?
推薦答案
PDO 的默認行為是在調用構造函數之前設置屬性.在調用構造函數后設置獲取模式設置屬性時,在位掩碼中包含PDO::FETCH_PROPS_LATE
,這將導致在未定義的屬性上調用__set
魔術方法.
The default behavior of PDO is to set the properties before invoking the constructor. Include PDO::FETCH_PROPS_LATE
in the bitmask when you set the fetch mode to set the properties after invoking the constructor, which will cause the __set
magic method to be called on undefined properties.
$st->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Foo');
或者,創建一個實例并將其提取到其中(即將提取模式設置為 PDO::FETCH_INTO
).
Alternatively, create an instance and fetch into it (i.e. set fetch mode to PDO::FETCH_INTO
).
這篇關于使用 PDO::FETCH_CLASS 和魔術方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!