How to add property to object in PHP >= 5.3 strict mode without generating error

Solution 1:

If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass objects (I believe) is when you cast an array as an object or when you create a new stdClass object from scratch (and of course when you json_decode() something - silly me for forgetting!).

Instead of:

$foo = new StdClass();
$foo->bar = '1234';

You'd do:

$foo = array('bar' => '1234');
$foo = (object)$foo;

Or if you already had an existing stdClass object:

$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;

Also as a 1 liner:

$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );

Solution 2:

Do it like this:

$foo = new stdClass();
$foo->{"bar"} = '1234';

now try:

echo $foo->bar; // should display 1234

Solution 3:

If you want to edit the decoded JSON, try getting it as an associative array instead of an array of objects.

$data = json_decode($json, TRUE);