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

It should be simple, but I can not find the answer ....

I have a generic stdClass $foo object with no properties. I want to add a new $bar property to it that is not yet defined. If I do this:

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

PHP is complaining in strict mode.

What is the correct way (outside the class declaration) to add a property to an already created object?

NOTE. I want the solution to work with a generic PHP object like stdClass.

A little bit about it. I am decoding a json string, which is an array of json objects. json_decode() generates an array of a StdClass object. I need to manipulate these objects and add a property to each.

+52
php class
Jul 23 '12 at 18:32
source share
7 answers

If you absolutely need to add a property to an object, I believe that you can use it as an array, add your property (like a new array), and then discard it as an object. The only time you run stdClass objects (I think) is when you throw the array as an object or when you create a new stdClass object from scratch (and, of course, when you json_decode() something - it's silly to forget me!).

Instead:

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

You would do:

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

Or, if you already have an existing stdClass object:

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

Also as 1 liner:

 $foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) ); 
+70
Jul 23 '12 at 18:45
source share

Do it like this:

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

now try:

 echo $foo->bar; // should display 1234 
+36
Sep 15 '15 at 8:55
source share

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

 $data = json_decode($json, TRUE); 
+10
Jul 23 '12 at 18:57
source share

you should use the magic methods __Set and __get. A simple example:

 class Foo { //This array stores your properties private $content = array(); public function __set($key, $value) { //Perform data validation here before inserting data $this->content[$key] = $value; return $this; } public function __get($value) { //You might want to check that the data exists here return $this->$content[$value]; } } 

Of course, don't use this example like this: no security whatsoever :)

EDIT: saw your comments, there might be an alternative based on reflection and decorator:

  class Foo { private $content = array(); private $stdInstance; public function __construct($stdInstance) { $this->stdInstance = $stdInstance; } public function __set($key, $value) { //Reflection for the stdClass object $ref = new ReflectionClass($this->stdInstance); //Fetch the props of the object $props = $ref->getProperties(); if (in_array($key, $props)) { $this->stdInstance->$key = $value; } else { $this->content[$key] = $value; } return $this; } public function __get($value) { //Search first your array as it is faster than using reflection if (array_key_exists($value, $this->content)) { return $this->content[$value]; } else { $ref = new ReflectionClass($this->stdInstance); //Fetch the props of the object $props = $ref->getProperties(); if (in_array($value, $props)) { return $this->stdInstance->$value; } else { throw new \Exception('No prop in here...'); } } } } 

PS: I have not tested my code, just a general idea ...

+1
Jul 23 '12 at 18:37
source share

I don't know if its a newer version of php, but it works. I am using php 5.6

  <?php class Person { public $name; public function save() { print_r($this); } } $p = new Person; $p->name = "Ganga"; $p->age = 23; $p->save(); 

This is the result. The save method actually gets a new property

  Person Object ( [name] => Ganga [age] => 23 ) 
0
Dec 18 '15 at 7:49
source share

I always use this method:

 $foo = (object)null; //create an empty object $foo->bar = "12345"; echo $foo->bar; //12345 
0
Aug 17 '16 at 18:18
source share

Yes, it is possible to dynamically add properties to a PHP object.

This is useful when a partial object is obtained from javascript.

JAVASCRIPT Side:

 var myObject = { name = "myName" }; $.ajax({ type: "POST", url: "index.php", data: myObject, dataType: "json", contentType: "application/json;charset=utf-8" }).success(function(datareceived){ if(datareceived.id >= 0 ) { /* the id property has dynamically added on server side via PHP */ } }); 

PHP side:

 $requestString = file_get_contents('php://input'); $myObject = json_decode($requestString); // same object as was sent in the ajax call $myObject->id = 30; // This will dynamicaly add the id property to the myObject object 

OR EASY TO SEND DUMMY PROPERTY from javascript that you fill in PHP.

-2
Jul 19 '14 at 11:53 on
source share



All Articles