在类构造函数中设置动态属性

时间:2014-02-06 19:40:39

标签: php pdo

class QuestionVO {

public $qtype;

function __construct() { //echo $this->qtype; //it's not empty and displays value
    $this->{$this->qtype} = true;
}

pdo声明

$statement->setFetchMode(\PDO::FETCH_CLASS, get_class(new QuestionVO()));

这是致命的错误。

然而,该文件在http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059说 “这个fetch方法允许您直接将数据提取到您选择的类中。当您使用FETCH_CLASS时,在调用构造函数之前设置对象的属性。”

Fatal error</b>:  Cannot access empty property in QuestionVO

例如,如果$ qtype = truefalse

我需要为对象自动设置动态属性,因为truefalse = true。

3 个答案:

答案 0 :(得分:2)

您有以下代码

$statement->setFetchMode(\PDO::FETCH_CLASS, get_class(new QuestionVO()));

在这里,get_class(new QuestionVO())您将对象作为参数传递给get_class方法,所以请这样考虑:

$obj = new QuestionVO(); // <-- error is rising at this point of initialization
get_class($obj);

所以,它不是PDO,但你试图在PDO将属性设置为此类/对象之前手动创建该类的实例,直到PDO设置属性,它是一个空房。

答案 1 :(得分:0)

使用其他变量分两步完成:

class QuestionVO {

    public $qtype;

    function __construct() {
        $methodname = $this->qtype;
        $this->$methodname = true;
}

显然,$methodname必须已经填充,所以如果你在构造函数中传递它可能会更好:

class QuestionVO {

    public $qtype;

    function __construct($methodname) {
        $this->qtype = $methodname;
        $this->$methodname = true;
}

答案 2 :(得分:0)

在调用构造函数之前,PDO确实会填充对象。但是当你只是简单地调用new QuestionVO时,它就不会填充对象。

因此使用get_class(new QuestionVO())无效,无论如何也不需要这样做。只需命名该类,如下所示:

$statement->setFetchMode(\PDO::FETCH_CLASS, 'QuestionVO');

但是如果查询结果集中qtype的值为null,会发生什么?然后你又回到了同样的问题。

您应该将构造函数编码为不假设qtype已设置:

function __construct() {
    if (isset($this->qtype)) {
        $this->{$this->qtype} = true;
    }
}
相关问题