PDO PHP提取类 [英] PDO PHP Fetch Class

查看:60
本文介绍了PDO PHP提取类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在php中学习pdo,以便使数据库访问更轻松,更高效.我读到_class的一个解释是,在调用构造函数之前已设置了对象的属性,这是什么意思?任何方向都将不胜感激.

解决方案

这意味着使用PDO将结果返回到自定义对象时,需要设置与查询结果键相对应的成员变量. /p>

例如:

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可以将变量设置为超出其内部范围的对象.

如果您的用户类别如下:

class User
{
}

然后,由于未定义属性,PDO无法从范围之外设置值.

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.

解决方案

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.

such as:

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();
}

This way PDO can set the variables to the object outside of its internal scope.

if you user class was like so:

class User
{
}

then PDO Would not be able to set the values from outside the scope, as there are no properties defined.

这篇关于PDO PHP提取类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆