PHP object Singleton not working
I am programming a website backend in PHP and I need to encapsulate开发者_如何学C $_SESSION in a class. I've made my Session class a singleton but I am having trouble using it.
class Session
{
private static $instance;
public static $sessionID;
private function __construct()
{
session_start();
self::$sessionID = session_id();
}
public function Session() {
return Session::singleton();
}
public static function singleton()
{
if (!isset(Session::$instance)) {
Session::$instance = new Session();
}
return Session::$instance;
}
public function destroy()
{
foreach ($_SESSION as $var => $val) {
$_SESSION[$var] = null;
}
session_destroy();
}
public function __clone()
{
trigger_error('Clone is not allowed for '.__CLASS__,E_USER_ERROR);
}
public function __get($var)
{
return $_SESSION[$var];
}
public function __set($var,$val)
{
return ($_SESSION[$var] = $val);
}
public function __destruct()
{
session_write_close();
}
public function exist( $var ) {
return isset($_SESSION[ $var ]);
}
}
Works fine 95% of the time. But occasionnaly when I invoke var_dump(Session::singleton());
output : object(Session)#2 (0) { }
It seems to me obvious that it is making another instance of my Session class, but I don't see exactly how it is possible.
Thanks a lot!
Try removing the public constructor (leaving only the private one)
public function Session() {
return Session::singleton();
}
I'm not 100% sure that will do it but having a public constructor does not adhere to the Singleton pattern
The '#2' (after 'object(Session)') is not number of instance of Session class but it's next number of object created by php. If You get #2 it seems that You've created something(object) before. I've tested Your class and when I run "var_dump(Session::singleton());" I get: "object(Session)#1 (0) { }" but when I run it at end of script I get (for example): "object(Session)#31 (0) { }"
Regards
精彩评论