返回值

参见

User Contributed Notes 7 notes

Be warned of the rather unorthodox behavior of PDOStatement::fetchObject() which injects property-values BEFORE invoking the constructor - in other words, if your class initializes property-values to defaults in the constructor, you will be overwriting the values injected by fetchObject() !

A var_dump($this) in your __construct() method will reveal that property-values have been initialized prior to calling your constructor, so be careful.

For this reason, I strongly recommend hydrating your objects manually, after retrieving the data as an array, rather than trying to have PDO apply properties directly to your objects.

Clearly somebody thought they were being clever here - allowing you to access hydrated property-values from the constructor. Unfortunately, this is just not how OOP works - the constructor, by definition, is the first method called upon construction.

If you need to initialize your objects after they have been constructed and hydrated, I suggest your model types implement an interface with an init() method, and you data access layer invoke this method (if implemented) after hydrating.

It should be mentioned that this method can set even non-public properties. It may sound strange but it can actually be very useful when creating an object based on mysql result.Consider a User class:

<?phpclass User {// Private propertiesprivate $id, $name;

private function __construct () {}

public static function load_by_id ($id) {$stmt = $pdo->prepare('SELECT id, name FROM users WHERE id=?');$stmt->execute([$id]); return $stmt->fetchObject(__CLASS__); }/* same method can be written with the "name" column/property */}

$user = User::load_by_id(1);var_dump($user);?>

fetchObject() doesn't care about properties being public or not. It just passes the result to the object. Output is like:

// Create an empty user and then delete it immediately$user = new User();$user->insert();$user->delete();?>The DataObject class example:<?php class DataObject { private $changedFields = array(); // list of updated fieldsprivate $data = array(); // original row from PDOStatementprivate $funcFields = array(); // fields that use MySQL functions // The properties above are private in this class, so even if in your subclass you define some properties named the same, or you associate a property of the same name with a field in your table, they will never influence these properties.function __get($property) { if (isset($this::$_propertyList[$property])) { return $this->data[$this::$_propertyList[$property]]; // access fields by PHP properties} else { return $this->$property; // throw the default PHP error} } function __set($property, $value) { if (isset($this::$_propertyList[$property])) {$field = $this::$_propertyList[$property];$this->data[$field] = $value; // update $data