2013-03-04 31 views
3

PDO::FETCH_CLASS允许使用预填充数据初始化类实例。它看起来是这样的:在构造函数被调用之前,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来调用构造函数被触发setter方法之前。

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

回答

0

对于这个工作,我这样做:

我在超这个声明魔术方法

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

它工作得很好,我

相关问题