I assign the result of an SQL query using PDO (
PDO::FETCH_OBJ ) to a variable, and with that variable I access the query values as if it were an object.
Example of an array as an object:
<?php $obj = (object) array('foo' => 'bar', 'property' => 'value'); echo $obj->foo; // prints 'bar' echo $obj->property; // prints 'value' ?>
If the query returns me empty and I want to manually assign this key a value and an object value, how do I do it?
Two ways to do this:
// 1: cast para object $obj = (object) array(); $obj->foo = 10; var_dump($obj); // 2: instância de stdClass $o = new stdClass(); $o->foo = 'bar'; var_dump($o);
In short, just assign something to a property and it will exist in the object.
And clarifying, there is no “array of type object” or “array of type stdClass”. What you do with
(object) is convert to object. If that is no longer an object, it is simply an object (or instance of
stdClass ), not an “object of type x”.