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.
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
stdClassobjects (I believe) is when you cast an array as an object or when you create a newstdClassobject from scratch (and of course when youjson_decode()something – silly me for forgetting!).Instead of:
You’d do:
Or if you already had an existing stdClass object:
Also as a 1 liner: