Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PDO::FETCH_CLASS with Magic Methods

I have a class that uses magic methods to store properties. Here is a simplified example:

class Foo {
    protected $props;

    public function __construct(array $props = array()) {
        $this->props = $props;
    }

    public function __get($prop) {
        return $this->props[$prop];
    }

    public function __set($prop, $val) {
        $this->props[$prop] = $val;
    }
}

I'm trying to instantiate objects of this class for each database row of a PDOStatement after it's executed, like this (doesn't work):

$st->setFetchMode(PDO::FETCH_CLASS, 'Foo');

foreach ($st as $row) {
    var_dump($row);
}

The problem is that PDO::FETCH_CLASS does not seem to trigger the magic __set() method on my class when it's setting property values.

How can I accomplish the desired effect using PDO?

like image 926
FtDRbwLXw6 Avatar asked Jan 17 '12 17:01

FtDRbwLXw6


1 Answers

The default behavior of PDO is to set the properties before invoking the constructor. Include PDO::FETCH_PROPS_LATE in the bitmask when you set the fetch mode to set the properties after invoking the constructor, which will cause the __set magic method to be called on undefined properties.

$st->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Foo');

Alternatively, create an instance and fetch into it (i.e. set fetch mode to PDO::FETCH_INTO).

like image 195
outis Avatar answered Nov 19 '22 00:11

outis