The full question should be "Is this correct or is it some bug I can't count on?"
WHY is this correct behavior?
I've been working with PDO more and in particular playing with fetching data directly into objects. While doing so I discovered this:
If I fetch data directly into an object like this:
$STH = $DBH->prepare('SELECT first_name, address from people WHERE 1');
$obj = $STH->fetchAll(PDO::FETCH_CLASS, 'person');
and have an object like this:
class person {
public $first_name;
public $address;
function __construct() {
$this->first_name = $this->first_name . " is the name";
}
}
It shows me that the properties are being assigned before the __construct is being called -- because the names all have " is the name" appended.
Is this some bug (in which case I can't/won't count on it) or is this The Way It Should Be. Because it's really quite a nice thing the way it works currently.
Update
Apparently, according to one of the maintainers this is not a bug. Someone posted it as a bug in 2008, to which the reply was 'its not a bug, read the docs'.
However, I'd really like to know WHY this is correct behavior.
After much reading I think I finally came across the answer: it works this way intentionally, and you have the option of making it operate otherwise.
There's a mostly undocumented PDO constant called
PDO::FETCH_PROPS_LATE
which you can use to cause the properties to be fetched into the object after its been constructed. For example:Will cause the properties to be assigned AFTER the object is created, so my example above would not modify the properties at all. Leaving the
PDO::FETCH_PROPS_LATE
off, of course, causes it to act as described in my example in the original question.The maintainers seem to have actively considered that both behaviors may be desirable and given you the option to do either. The documentation doesn't even explain it -- I was reading through a list of PDO constants and saw it, and gave it a shot.