Returning by Reference Question


<?php
class Auth {
  static public function authenticate($user, $passwd) {
    //.......
    if($result) {
      $_SESSION['auth'] = serialize($userObject);
      return true;
    } 
    return false;
  }
  
  static public function &getAuthUser()
  {
     return unserialize($_SESSION['auth']);
  }
}

Auth::authenticate();
$userObject = &Auth::getAuthUser();
$userObject->name = "test";

echo $userObject->name;  //test
echo $_SESSION['auth']->name; //original name

?>

Right now I have to manually update the SESSION each time I make a change to the user object so that the change is also reflected in the SESSION.

And it seems like the pseudo code won’t work due to the unserialize() which makes sense…

I would like any changes to the $userObject to be reflected in the SESSION automatically.

I’m thinking this may not be possible because of the explicit serialize/unserialize, but I’d thought I’d throw it out there just in case.

So any suggestions are welcomed.

Thanks!

Notes:
I have to explicitly call serialize and unserialize because it seems like in php 5.1 (can’t upgrade), the __sleep and __wakeup magic functions aren’t invoked automatically when setting an obj to a SESSION var. In 5.2, everything seems to work just fine.

Forget the reference stuff…
Just do $_SESSION[‘auth’] = unserialize( $whatever );

I probably didn’t explain my problem that well but that won’t work for my case :frowning:

I have an PDO instance inside $whatever which can’t be serialized. And by default when you assign an object to a session, it will try to serialize it before writing. The result was a corrupt serialized string that couldn’t be unserialized.

So in my __sleep method, I unset the PDO instance and in my __wakeup I re instantiate it.

However because I have to explicitly call serialize/unserialize to trigger the magic functions (php 5.1 thing), the variable the session is assigned to isn’t by reference. So I have to manually reset the SESSION each time I made a change to the user object.

Maybe I can do something with the session handlers…

Thanks for the suggestion though!