本文介紹了PDO 的 FETCH_INTO $這個類不起作用的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想使用 PDO 的 FETCH_INTO
的構造函數填充類:
I want to populate class with constructor using FETCH_INTO
of PDO:
class user
{
private $db;
private $name;
function __construct($id)
{
$this->db = ...;
$q = $this->db->prepare("SELECT name FROM users WHERE id = ?");
$q->setFetchMode(PDO::FETCH_INTO, $this);
$q->execute(array($id));
echo $this->name;
}
}
這不起作用.沒有錯誤,只是沒有.腳本沒有錯誤,FETCH_ASSOC
工作正常.
This does not work. No error, just nothing. Script has no errors, FETCH_ASSOC
works fine.
FETCH_INTO
有什么問題?
推薦答案
您的代碼中有兩個錯誤:
You have two errors in your code:
1) 你忘記了 $q->fetch()
1) You forgot $q->fetch()
...
$q->execute(array($id));
$q->fetch(); // This line is required
2) 但即使在添加 $q->fetch() 之后你也會得到這個:
2) But even after adding $q->fetch() you'll get this:
致命錯誤:無法訪問私有屬性 User::$name in ...
Fatal error: Cannot access private property User::$name in ...
因此,如您所見,即使在類方法內部調用 PDO,它也無法訪問私有成員.
So, as you can see, PDO cannot access private members even if it is called inside class method.
這是我的解決方案:
...
$q->execute(array($id));
$q->setFetchMode(PDO::FETCH_ASSOC);
$data = $q->fetch();
foreach ($data as $propName => $propValue)
{
// here you can add check if class property exists if you don't want to
// add another properties with public visibility
$this->{$propName} = $propValue;
}
這篇關于PDO 的 FETCH_INTO $這個類不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!