SunshinePHP Developer Conference 2015

PDOStatement::fetchObject

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.4)

PDOStatement::fetchObjectObtiene la siguiente fila y la devuelve como un objeto

Descripción

public mixed PDOStatement::fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )

Obtiene la siguiente fila y la devuelve como un objeto. Esta función es una alternativa para PDOStatement::fetch() con el estilo PDO::FETCH_CLASS o PDO::FETCH_OBJ.

Parámetros

class_name

El nombre de la clase creada.

ctor_args

Los elementos de este array son pasados al constructor.

Valores devueltos

Devuelve una instancia de la clase requerida con los nombres de sus propiedades que se corresponden a los nombre de las columnas, o FALSE en caso de error.

Ver también

add a note add a note

User Contributed Notes 2 notes

up
27
rasmus at mindplay dot dk
1 year ago
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.
up
-1
Vegard Lkken
7 months ago
Because of the injection of object properties before the constructor is executed, I usually build my classes like this to make sure already set properties aren't overwritten:

<?php
class Person {
  public
$name;
  public
$age;
  public
$sex;

  public function
__construct($name=NULL, $age=NULL, $sex=NULL) {
   
$this->name = $name === NULL ? $this->name : $name;
   
$this->age = $age === NULL ? $this->age : $age;
   
$this->sex = $sex === NULL ? $this->sex : $sex;
  }
}
?>
To Top