Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
417 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...