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.
Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .
Properties of ObjectThese variables can be public, protected or private. By default, the public is used. The value of a variable may or may not contain a default value, meaning that the variable may be initialized with a value or not. The variable names are case sensitive, meaning that $name is different from $Name.
Introduction. Data members declared inside class are called properties. Property is sometimes referred to as attribute or field. In PHP, a property is qualified by one of the access specifier keywords, public, private or protected.
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.
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' ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With