serialize the values of a php ArrayObject

457 Views Asked by At

Can anyone tell me the difference between s1 and s2:

<?php
$o = new ArrayObject();

$s1 = serialize($o);
$s2 = $o->serialize();

var_dump($s1);
var_dump($s2);
?>

The above example will output:

string(45) "C:11:"ArrayObject":21:{x:i:0;a:0:{};m:a:0:{}}"

string(21) "x:i:0;a:0:{};m:a:0:{}"

In my case i want an arrayobject with only its values serialized not the whole object; something like

array( serialized_value_1, serialized_value_2, serialized_value_3, serialized_value_4, serialized_value_5, )

is there an easy way to do this or i should loop in the array and serialize them 1 by 1???

for example i need

$arrayObject[0] = serialized_value_0;
$arrayObject[1] = serialized_value_1;
$arrayObject[2] = serialized_value_2;
$arrayObject[3] = serialized_value_3;

and not serialize($arrayObject) which will serialize the whole object...

i want to use serialize because it easier to comapre 2 object which are not from the same instance... example:

$p1 = new People('John');
$p2 = new People('John');

so $p1 != $p2

but serialize($p1) == serialize($p2)

1

There are 1 best solutions below

3
On

You don't want to serialize two array objects, you want to compare them. That is something completely different.

And in fact, you don't really need to do something. I have this test code working for me:

$obj1 = new ArrayObject(array('John'));
$obj2 = new ArrayObject(array('John'));

var_dump($obj1 === $obj2); // false - obvious, not the same instance
var_dump($obj1 == $obj2); // true - equality comparison works
var_dump((array) $obj1 === (array) $obj2); // true - casting to array compares ...
var_dump((array) $obj1 == (array) $obj2); // true - ... the array content

This will also work as long as you correctly extend the ArrayObject in your People class. You have to store all array values inside the original ArrayObject, i.e. pass all values to the inner, parent functions, if you'd implemented any of the array access in People yourself.