問題描述
我正在 php 中學習 pdo,以便使數據庫訪問更容易和更高效.我讀過的一個關于 fetch _class 的解釋是你的對象的屬性是在調用構造函數之前設置的.這是什么意思?任何方向都非常感謝.
I am learning pdo in php , so as to make database access easier and more efficient .One explanation i have read for fetch _class is that The properties of your object are set BEFORE the constructor is called.What does this mean? Any direction is greatly appreciated.
推薦答案
這意味著在使用 PDO 將結果返回到自定義對象時,需要設置查詢結果鍵對應的成員變量.
This means that when using PDO to return a result into a custom object, you are required to set out the member variables which correspond to the query result keys.
例如:
class User
{
//Predefine Here
public $id;
public $username;
public $password;
public $email;
public $hash;
public function profileLink()
{
return sprintf('<a href="/profile/%s">%s</a>',$this->id,$this->username);
}
}
$result = $sth->fetchAll(PDO::FETCH_CLASS, "User");
foreach($result as $user)
{
echo $user->profileLink();
}
通過這種方式,PDO 可以將變量設置到其內部范圍之外的對象.
This way PDO can set the variables to the object outside of its internal scope.
如果你的用戶類是這樣的:
if you user class was like so:
class User
{
}
然后 PDO 將無法從范圍之外設置值,因為沒有定義屬性.
then PDO Would not be able to set the values from outside the scope, as there are no properties defined.
這篇關于PDO PHP 獲取類的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!