无法基于PHP中的单例序列化对象

时间:2010-09-23 19:50:44

标签: php serialization object singleton

我有一个基于Singleton设计的对象,我用它来进行用户身份验证。因为对象是每用户对象,所以我希望在执行结束时将对象自动存储在会话变量中。但是,每当我尝试在内部或外部序列化对象时,我都会得到一个空字符串。

以下是基本类,减去不相关的函数:

<?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
}
}
?>

每当我调用序列化对象时,无论是在__destroy方法内部使用serialize($ this)还是序列化(self :: $ _ instance),还是在外部使用serialize($ user),我都会得到一个空字符串。但是,我知道该对象存在,因为我可以从中获取有关经过身份验证的用户的数据。

1 个答案:

答案 0 :(得分:1)

魔术函数称为__destruct,而不是__destroy。完成;)