Assigning a key and a value to an object

3

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'

?>

Doubt:

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?

    
asked by anonymous 13.11.2014 / 00:40

1 answer

6

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);

link

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

    
13.11.2014 / 01:12