Maintaining state between runs | Session Use

后端 未结 1 1568
情话喂你
情话喂你 2021-01-26 10:32

There are different way to run PHP code. For example user initiate reloads and user initiated ajax requests.

What it the best way to maintain state between these runs?<

1条回答
  •  孤城傲影
    2021-01-26 10:57

    PHP does consider it separate runs. Two things:

    1. Don't use globals... they're bad :) Consider making your "session" class a collection of static functions with the session_id as a static member var.
    2. Simply create a new session class in your 2nd snippet:
    $obj_ses = new session();
    $obj_ses->activate('email', $this->_protected['email']);

    The session id will be the same across all page views for that particular user, so creating a new session() in the second snippet will still refer to the same session you started in the first snippet.

    Here's what a static implementation might look like:

    
    // class names should be camel-cased
    class SessionManager
    {
        protected static $session_id = null;
    
        public static function start()
        {
            self::$session_id = session_start();
        }
    
        // ... and so on
    }
    
    // to use
    SessionManager::start();
    SessionManager::activate('email', $email);
    

    That should really be all you need. There are certainly many ways to do this, but this ought to get you started :)

    0 讨论(0)
提交回复
热议问题