6

I am trying to store an object in Joomla session and it gets reset when I null the temp variable.

$whoami = new stdClass();
$whoami->type = 's'; $whoami->id = '1';

//Loading the value to session
$session->set('whoami',$whoami);

//Getting the session value to a temp variable
$temp = $session->get('whoami');
print_r($temp); //This prints correct as [type] => s [id] => 1
var_dump($temp);    

//Set the temp id to null
$temp->id = null;

//Again get the value from session
$test1 = $session->get('whoami');
print_r($test1);  // [type] => s [id] => 
var_dump($test1);   

var_dump of $temp and $test1 is as below

$temp

object(stdClass)#193 (2) {
  ["type"]=>
  string(1) "s"
  ["id"]=>
  string(1) "1"
}

$test1

object(stdClass)#193 (2) {
  ["type"]=>
  string(1) "s"
  ["id"]=>
  NULL
}

Assigning null to the temp id reset the value in the session variable... looks wierd...

Can someone please help.

  • Can you do a var_dump to make sure that $temp and $test1 are the same objects. It definitely looks weird, because object manipulation outside the session could not influence on this object in session. – Dmitry Rekun Sep 25 '15 at 10:24
  • @DmitryRekun Added the var_dump output in the question. Both the variables share the same resource number 193 – Malaiselvan Sep 26 '15 at 17:37
  • That's really odd :( I hope someone else will have an idea what is going on here... – Dmitry Rekun Sep 27 '15 at 6:29
4

It's simple, your var $temp is a reference of the session object. So if you change the content of the object you change the session object itself.

You have to clone the object:

$temp = clone $session->get('whoami');

or you create a new object:

$temp = new stdClass();
$temp->type = $session->get('whoami')->type;
$temp->id = $session->get('whoami')->id;

Your var dump should look like this now:

stdClass Object
(
    [type] => s
    [id] => 1
)
object(stdClass)#42 (2) {
  ["type"]=>
  string(1) "s"
  ["id"]=>
  string(1) "1"
}
1stdClass Object
(
    [type] => s
    [id] => 1
)
object(stdClass)#812 (2) {
  ["type"]=>
  string(1) "s"
  ["id"]=>
  string(1) "1"
}

Further information:

PHP Manual Object References

PHP Manual Object cloning

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.