3
I assign the result of an SQL query using PDO (PDO::FETCH_OBJ
) a variable, and with this variable I access the values of the query 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'
?>
Doubt:
If the query returns me empty and I want to manually assign in this array a key and a value as object, as I do?
Yes. Basically that. I thought I needed more code to assign a new key and value to an empty stdClass array.
– Gustavo Piucco
STD is an anonymous class, you can create the properties directly without problem
– Papa Charlie
In addition to being able to iterate such objects with conventional arrays because stdClass natively has the functionality provided by Traversable (although not responding to a
instanceof
). But ironically, it cannot have its items accessed with the array bracket notation because it does not even implement the functionality provided by the interface.– Bruno Augusto