Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a reference in PHP

I would like to know why my serialization in php does not work as expected:

<?
$x = "whatever...";
$y = array(&$x, "test, 1-2, 1-2...", &$x);
$yy = unserialize(serialize(&$y));
$y[0] = "blah";
echo($yy[0]); // prints 'whatever', was expecting 'blah'
?>
like image 715
d0bz Avatar asked Sep 17 '25 22:09

d0bz


2 Answers

The & is ignored by serialize.

It seems like you are trying to create a symbol table alias (reference) from y to yy, but you cannot do that here. When you pass &y to serialize, it does not treat the passed value as a reference or serialize in line. Moreover, it returns an entirely new value, not a reference to the original value. You would have to create the alias separately:

$yy = &$y;
$yy = unserialize(serialize($y));

I'm also not really sure what you're trying to do either, or what it has to do with serialization.

like image 153
Explosion Pills Avatar answered Sep 19 '25 15:09

Explosion Pills


As Explosion Pills' answer states, unserialize "returns an entirely new value". However, serialization will maintain "relative" references. (Technically, there is no such thing as a relative reference in PHP, but its a good way to conceptualize it.)

If you collect your referenced and referencing variables in an array, serializing the array will save the reference relationship. It won't maintain the original reference, but will automatically recreate it in the context of the new array returned by unserialize.

$vars = array();
$vars['x'] = 'initval';
$vars['xref'] =& $vars['x'];
$vars2 = unserialize( serialize( $vars ) );
$vars2['x'] = 'newval';
echo $vars2['xref']; // prints "newval"

It works the same way for internal references in objects.

like image 45
Stephen M. Harris Avatar answered Sep 19 '25 15:09

Stephen M. Harris