【问题标题】:How does PDO::FETCH_CLASS populate the object properties before the constructor is called?PDO::FETCH_CLASS 如何在调用构造函数之前填充对象属性?
【发布时间】:2013-03-04 10:26:40
【问题描述】:

PDO::FETCH_CLASS 允许使用预先填充的数据初始化类实例。它看起来像这样:

<?php
class Bar {
    private $data = [];

    public function __construct ($is) {
        // $is === 'test'
        // $this->data === ['foo' => 1, 'bar' => 1]
    }

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

$db
    ->query("SELECT `foo`, `bar` FROM `qux`;")
    ->fetchAll(PDO::FETCH_CLASS, 'Bar', ['test']);

或者,可以使用PDO::FETCH_PROPS_LATE 在触发设置器之前调用构造函数。

我很想知道 PDO 如何在调用构造函数之前通过 setter 填充 Class 实例,或者更具体地说,是否有办法复制这种行为?

【问题讨论】:

    标签: php pdo


    【解决方案1】:

    在 PHP 5.4+ 中可以使用 ReflectionClass::newInstanceWithoutConstructor 来做到这一点。

    【讨论】:

      【解决方案2】:

      为此,我这样做了:

      我在我的超类中声明了这个神奇的方法

        public function __set($name, $value) {
          $method = 'set' . str_replace('_', '', $name); //If the properties have '_' and method not
          if (method_exists($this, $method)) {
              $val = call_user_func(array($this, $method), $value);
          }
      }
      

      对我来说效果很好

      【讨论】:

        猜你喜欢
        • 2010-10-22
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 2014-07-29
        • 2010-09-24
        • 2018-06-11
        • 1970-01-01
        • 2022-11-21
        相关资源
        最近更新 更多