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

class, php

Solution

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

Problem

This has to be simple, but I can't seem to find an answer.... I have a generic stdClass object `$foo` with no properties. I want to add a new property `$bar` to it that's not already defined. If I do this: ``` $foo = new StdClass(); $foo->bar = '1234'; ``` PHP in strict mode complains. What is the proper way (outside of the class declaration) to add a property to an already instantiated object? NOTE: I want the solution to work with the generic PHP object of type stdClass. A little background on this issue. I'm decoding a json string which is an array of json objects. `json_decode()` generates an array of StdClass object. I need to manipulate these objects and add a property to each one.

Original source