0

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?

1 Answer 1

1

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:

$x = clone $session->get('tester_obj');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.