Serialize Data – PHP

If it absolutely required to add the property to the object, you could cast it as an array, add your property (as a new array key=>value), then cast it back as an object.
The only time you run into stdClass objects 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).

Instead of setting an stdClass() :

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

You’d create an array:

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

Or if there is already an existing stdClass object:

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

Also as a 1 liner:

$foo = (object) array_merge( (array)$foo, array( 'bar' => 'fooString' ) );

Output Example:

Or if there is already an existing stdClass object:

//$items = (object)[];
$items = new stdClass;
$items->one = "stringa";
$items->two = 152;
$items->thr = array('arr1' => 'item1', 'arr2' => 'itema2' );
$items->four = array('1', 2, '3',4);

$ser = serialize($items);
var_dump($ser);

string(179) 
"O:8:"stdClass":4:{
  s:3:"one";s:7:"stringa";
  s:3:"two";i:152;
  s:3:"thr";
    a:2:{s:4:"arr1";s:5:"item1";s:4:"arr2";s:6:"itema2";}
  s:4:"four";
    a:4:{i:0;s:1:"1";i:1;i:2;i:2;s:1:"3";i:3;i:4;}}"

Much like using JS stringify() method.

 

Was this article helpful?

Related Articles

Leave A Comment?