【问题标题】:PDO's FETCH_INTO $this class does not workPDO 的 FETCH_INTO $this 类不起作用
【发布时间】:2011-03-18 18:54:37
【问题描述】:

我想使用 PDO 的 FETCH_INTO 使用构造函数填充类:

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 工作正常。

FETCH_INTO 有什么问题?

【问题讨论】:

  • 我最近经历了这种定义对象的方式,对我来说使用 PDO 和 fetch 方法来填充对象是我能看到的最方便的方法。

标签: php pdo


【解决方案1】:

您的代码中有两个错误:

1) 你忘记了 $q->fetch()

 ...
 $q->execute(array($id));
 $q->fetch(); // This line is required

2) 但是即使在添加 $q->fetch() 之后,你也会得到这个:

致命错误:无法访问私有 属性 User::$name in ...

所以,如你所见,PDO 不能访问私有成员,即使它在类方法中被调用。

这是我的解决方案:

...
$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;
}

【讨论】:

  • 您也可以将$name 设为公共变量。听起来确实很像。
  • +这个例子很有帮助
  • 那仍然抛出同样的错误:Fatal error: Cannot access private property User::$name in ...
  • 需要添加访问器来设置私有变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多