0

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?

  • Does your AJAX handler load (or directly hit) the index.php at all? If that's the only place the object is instantiated, and the AJAX call does not invoke index.php in any way, then the object won't get created for your AJAX calls. – Marc B Mar 15 '11 at 19:13

1 Answers1

2

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 :)

Ian Selby
  • 3,241
  • 1
  • 25
  • 18
  • Globals, btw, are bad for many reasons, but they're also not too efficient. – Ian Selby Mar 15 '11 at 19:11
  • Remember that PHP is essentially stateless... nothing is shared between requests... so a static class in one request won't be shared with another (even if they're concurrent). I'll update my answer above to answer your second question – Ian Selby Mar 15 '11 at 20:37