In this case, you do not need to define a constructor. When you use PDOStatement::fetchObject
to determine which object will be used to represent the data coming from a query, the PDO
will define the values to the properties directly, from the way that a simple array
.
To understand this, you first need to understand that in PHP, for you to define a value of a class property, you don’t need to declare it in the class. You can simply assign directly, of course, as long as it has not been declared in the class as protected
or private
.
Behold:
Obj {
public $nome;
}
$obj = new Obj;
$obj->nome = "Wallace"; // declarado
$obj->idade = 26; // Não declarado
var_dump($obj);
The result is :
object(Obj)#168 (2) {
["nome"]=>
string(7) "Wallace"
["idade"]=>
int(26)
}
Using magical methods
When you asked about the definition in the constructor, it was completely understandable that you want to add a behavior to your class to define how the values will be defined.
As has been said, with the builder this is not possible, because the PDOStatement::fetchObject
does not use the constructor, but it will assign the values one by one (externally, so to speak).
The solution to dribbling this problem is using the magic method called __set
. With it you determine a behavior for your class when a property is not declared or accessible in your object.
Example:
public function Obj {
protected $items;
public function __set($key, $value) {
$this->items[$key] = $value;
}
}
So the results would be different.
Behold:
$obj = new Obj;
$obj->nome = "Wallace";
$obj->idade = 26;
object(Obj)#165 (1) {
["items":protected]=>
array(2) {
["nome"]=>
string(7) "Wallace"
["idade"]=>
int(26)
}
}
Using the builder
If you want to use the constructor, you will have to pass the desired results manually to the constructor.
$array = $stmt->fetch(PDO::FETCH_ASSOC);
new Obj($array);
+1 because the question is very good. I also had much this doubt.
– Wallace Maxters