2010-09-23 47 views
2

我有一个基于Singleton设计的对象,用于用户身份验证。由于该对象是每个用户对象,我希望对象在执行结束时自动存储在会话变量中。但是,任何时候我尝试序列化对象,无论是内部还是外部,我都会得到一个空字符串。无法基于PHP中的单例序列化对象

以下是基本类,减去不相关的功能:

<?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方法(个体经营:: $ _instance)或外部使用序列化($ user),我得到一个空字符串。但是,我知道该对象存在,因为我可以从中获取有关经过身份验证的用户的数据。

+0

它可以序列化它不是一个单身。 – Gordon 2013-02-13 17:30:43

回答

1

魔术功能被称为__destruct,而不是__destroy。完成;)

+0

非常感谢,非常感谢。 D'哦! – Wige 2010-09-23 20:31:35

+0

呵呵,这些名字是如此相似/可信我在一刻钟的好一段时间里为什么它不起作用,我也在摸不着头脑;) – Wrikken 2010-09-23 21:11:51