0

When I store object to a session in PHP 5.3 and then trying to change its properties they also changed in session array. Why it so? Explain me please!

My code:

<?php 
class Z {
    public $val;
}
session_start();
$z = new Z();
$z->val = 10;
$_SESSION['z'] = $z;
$z->val++;
print_r($_SESSION);
?>

Result:

Array ([z] => Z Object ( [val] => 11 ) ) 
mephis
  • 3
  • 1

1 Answers1

3

PHP is not creating a copy of the object, but rather storing a reference in session.

If you want a copy, use clone():

$_SESSION['z'] = clone $z;
jszobody
  • 28,495
  • 6
  • 61
  • 72
  • And what about that, when my php-script finished, does object removes form memory but stays at session? My session stores to file. – mephis Nov 21 '13 at 22:07
  • @user3019468 Once you put something in session, it stays there until the session is destroyed or you remove it yourself. Use `unset($_SESSION['z'])` to remove it yourself. – jszobody Nov 21 '13 at 22:08
  • yeah, thanks for that. but i wonder, when my script finishes, is any object `$z` stays in RAM? if not, then `$_SESSION['z']` has a link to non-existing object `$z` ? – mephis Nov 21 '13 at 22:13
  • As you pointed out, your session is stored in a file (a tmp file). So no it doesn't stay in RAM. PHP automatically serializes any objects that are in session at the end of your script, and automatically unserializes them at the beginning of the next request. – jszobody Nov 21 '13 at 22:17
  • You said that `$_SESSION['z']` - is a refference to `$z`. So when script finishes, real `$z` destroys from RAM, right? But it's "copy" in `$_SESSION['z']` serializes and stores to tmp file. When I start a new another script `$_SESSION['z']` would be a new object in memory. Am I right? – mephis Nov 21 '13 at 22:34
  • Whether you store a reference to your initial object or to a clone of that object, PHP will serialize it at the end of session and store the data in the tmp file, and unserialize it at the beginning of the next session. After it is unserialized the object will have the same state as before, same values. – jszobody Nov 21 '13 at 22:36
  • So it even serializes a reference to object at the end... Thanks a lot, you really helped me! – mephis Nov 21 '13 at 22:41