0

I am working on a simple anonymous login system and I have a Session class which looks like this:

<?php

class Session
{
    private static $cookieLifeSpanInDays;

    public function __construct()
    {
        self::$cookieLifeSpanInDays = 1825;
    }

    public static function loginUser()
    {
        if (!Session::isLoggedIn())
        {
            // Login User
            $session_id = Session::newSessionId();
            $name = Session::newUserName($session_id);
            if (empty($name))
                throw new Exception('Failed to generate a unique user name. Try again later.');
            DB::insert('users', array(
                'name'          => $name,
                'session_id'    => $session_id,
                'last_login'    => time()
            ));
            setcookie("sessionId", $session_id, time() + (self::$cookieLifeSpanInDays * 86400), '/', $_SERVER['HTTP_HOST']);
            $_SESSION['isLoggedIn'] = true;

            var_dump(self::$cookieLifeSpanInDays);
            var_dump($_COOKIE);
            exit();
        }

        // Defaults
        return true;
    }
}

When I call the class like this: Session::loginUser();

The var_dumps() in the loginUser function looks like this:

enter image description here

So, my login function is broken (no cookie is getting set) because the static property on class self::$cookieLifeSpanInDays is null. What am I doing wrong here?

Latheesan
  • 23,247
  • 32
  • 107
  • 201
  • 1
    Constructors are functions in a class that are automatically called when you create **a new instance of a class with new**. http://www.php.net/manual/ru/oop4.constructor.php – Phantom Jul 07 '14 at 09:35
  • so, I can't use constructors on a static class - since I never create an instance of the class? I set the property value directly like this: `private static $cookieLifeSpanInDays = 1825;` and then when I call the login function, the cookie still isn't getting set. – Latheesan Jul 07 '14 at 09:37

1 Answers1

0

I've fixed it:

<?php

class Session
{
    private static $cookieLifeSpanInDays = 1825;

    public static function loginUser()
    {
        if (!Session::isLoggedIn())
        {
            // Login User
            $session_id = Session::newSessionId();
            $name = Session::newUserName($session_id);
            if (empty($name))
                throw new Exception('Failed to generate a unique user name. Try again later.');
            DB::insert('users', array(
                'name'          => $name,
                'session_id'    => $session_id,
                'last_login'    => time()
            ));
            setcookie("sessionId", $session_id, time() + (self::$cookieLifeSpanInDays * 86400));
            $_SESSION['isLoggedIn'] = true;

            var_dump(self::$cookieLifeSpanInDays);
            var_dump($_COOKIE);
            exit();
        }

        // Defaults
        return true;
    }
}
Latheesan
  • 23,247
  • 32
  • 107
  • 201