Assigning a key and a value to an object

Posted on

Question :

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:


$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?


Answer :

Two ways to do this:

// 1: cast para object
$obj = (object) array();
$obj->foo = 10;

// 2: instância de stdClass
$o = new stdClass();
$o->foo = 'bar';


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”.


Leave a Reply

Your email address will not be published. Required fields are marked *