I'm using the Concrete CMS which leverages the Symfony-HTTP-foundation component for Session management. I have everything working, but I'm curious about some strange behavior I'm seeing. Take this example:
if (!is_null($session)) {
if ($session->has('tester_obj')) {
$x = $session->get('tester_obj');
$x->name = 'alex';
$x->age = 40;
var_dump($session->get('tester_obj'));
} else {
echo 'nope';
$x = new \stdClass();
$x->name = 'Steve';
$session->set('tester_obj', $x);
}
}
If you look at the "if" statement, when the session HAS the key tester_obj you can see I retrieve the value in the next line (by setting $x using $session->get('tester_obj') ). However, I go on to modify the name (changed to alex) and add age, but I do NOT call $session->set again to replace the session variable with the updated object, but the variable saved in the session now contains "alex" and "40" even though I never replaced the session variable "tester_obj" with the modified object. Why is this happening?
Because objects are passed by reference in PHP.
If you want to play with a copy of the object then you need to create a new object containing the same data: