【问题标题】:Set a dynamic property in the class constructor在类构造函数中设置动态属性
【发布时间】:2014-02-06 19:40:39
【问题描述】:
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。

【问题讨论】:

  • 先设置$this-&gt;qtype的值。
  • 好吧$qtype 永远不会是"truefalse",对吗?它可能默认为null。这个类是否继承了设置$qtype的地方?
  • 我已经编辑了我的问题,属性是在调用构造函数之前由 PDO 设置的\

标签: php pdo


【解决方案1】:

你有以下代码

$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 设置属性,它是一个空属性。

【讨论】:

    【解决方案2】:

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

    所以使用get_class(new QuestionVO()) 是行不通的,而且你也不需要这样做。只需命名类,如下所示:

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

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

    您应该编写您的构造函数以不假定 qtype 已设置:

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

    【讨论】:

      【解决方案3】:

      使用附加变量分两步完成:

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

      【讨论】:

      • 如果属性是由 PDO 设置的,我已经修改了问题
      • 那么应该没问题,因为PDO 填充了您的实例BEFORE 调用了构造函数。尝试首先第一个sn-p,如果没有帮助,再尝试另一个。
      • 另外:在设置动态属性之前和之后尝试在构造函数中执行 var_dump(this)。
      • 同样的错误,无法访问空属性(我无法传入构造函数,因为它是由 PDO 调用的)
      • 试过 var_dump($this),它对所有属性都显示 NULL,但是,echo $this->qtype 显示一个有效值
      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多