我正在学习pdo中的pdo,以便使数据库访问更容易和更有效.我读过fetch _class的一个解释是你的对象的属性是在调用构造函数之前设置的.这是什么意思?任何方向都非常感谢.
Rob*_*itt 45
这意味着当使用PDO将结果返回到自定义对象时,您需要设置与查询结果键对应的成员变量.
如:
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();
}
Run Code Online (Sandbox Code Playgroud)
这样,PDO可以将变量设置为其内部范围之外的对象.
如果您的用户类是这样的:
class User
{
}
Run Code Online (Sandbox Code Playgroud)
然后PDO将无法从范围外设置值,因为没有定义属性.
Kri*_*ris 34
假设你有这个代码的snippit
<?php
class Foo {
public $bar;
public function __construct()
{
$this->bar = 1;
}
}
$stmt = $dbh->prepare("SELECT bar FROM foo");
$stmt->setFetchMode(PDO::FETCH_CLASS, 'Foo');
$stmt->execute();
$obj = $stmt->fetch()
?>
Run Code Online (Sandbox Code Playgroud)
$ obj的条形图将被设置为"1"而不是从数据库中检索到的内容.
如果您希望将其设置为数据库而不是"1"的结果,则可以将获取模式更改为
$stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Foo');
Run Code Online (Sandbox Code Playgroud)
这会导致在将结果分配给属性之前调用构造函数