0

I am programming a website backend in PHP and I need to encapsulate $_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!

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, there's no reason for that to be there. The code isn't compatible with PHP4 so there's no reason to have a PHP4-style constructor.
Thanks, I will remove it but it where there only for fixing reason. Another site suggested to write to fix the problem. Problem is still there.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.