views:

28

answers:

1

I have an object, based on the Singleton design, that I use for user authentication. Because the object is a per-user object, I want the object to be stored automatically in a session variable at the end of execution. However, any time I try to serialize the object, either internally or externally, I get an empty string.

The following is the basic class, minus irrelevant functions:

<?php
/**
* The user class is intended to handle information about authenticated users. Information contained in this class is to be stored
* in SESSION['session_user'] as a serialized object.
*/
class User {
 // Reference to the single User instance
 private static $_instance;
 // User levels
 const GUEST = 0;
 const USER = 1;
 const ADMINISTRATOR = 3;
 // Information about the account
 private $_username;
 private $_userid;
 private $_userlevel;
 // Information about the user, for preventing session hijacking
 private $_ipaddress;
 private $_useragent;

 private function __construct() {
  // Set the visitor's information
  // Set the default information
 }

 public static function getUser() {

  // Check if a user object has been created
  if (!isset(self::$_instance)) {
   // Check if the object is stored in the user session
   if (isset($_SESSION['session_user'])) {
    self::$_instance = unserialize($_SESSION['session_user']);
    //unset($_SESSION['session_user']);
    echo 'Unserializing user';
   } else {
    $c = __CLASS__;
    self::$_instance = new $c;
    echo 'Creating new user';
   }
 }
 return self::$_instance;
}

function __wakeup() {
 // First, check that the user agent has not changed
 // Check that the IP has not changed
}

function __destroy() {
 $_SESSION['session_user'] = serialize(self::$_instance);
 echo serialize(self::$_instance);
 print_r($_SESSION);
}
public function __set($index, $value) {
 return NULL;
}
public function __get($index) {
 // Determine which value to return
}
public function authenticate($inUsername, $inPassword) {
 // Authenticate the user
}
}
?>

Any time I call serialize on the object, either internally in the __destroy method using serialize($this) or serialize(self::$_instance), or externally using serialize($user), I get an empty string. However, I know the object exists since I can get data out of it about an authenticated user.

+1  A: 

The magic function is called __destruct, not __destroy. Done ;)

Wrikken
Verily, thank you very much. D'oh!
Wige
Hehe, the names are so alike / believable I also was scratching my head for the better part of a quarter of an hour why it didn't work ;)
Wrikken