Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

class

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.

like image 640
Ray Avatar asked Jul 23 '12 18:07

Ray


People also ask

How do you access the properties of an object in PHP?

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 .

What are the properties of object in PHP?

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.

What is declaring properties in PHP?

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.

What is stdClass?

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.


1 Answers

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' ) ); 
like image 111
WWW Avatar answered Sep 21 '22 12:09

WWW