- Yes.
- No, if by page Y you mean a separate request from the client.
The only way to persist data between page requests is to use sessions (or cookies). Any objects you've created and any changes you've made to static class variables (or fields, as they're commonly called) will be lost.
What you probably need to do is store some information as session data (using the $_SESSION
superglobal; see the link above) and use this to initialize your objects and static fields at the beginning of each request.
This is easily done by way of a separate PHP file that handles all your initialization for you. For example, you might include this at the beginning of all your scripts if you wanted to persist an object of type Foo
:
<?php
session_start();
// Get some session data that you've previously set.
if (isset($_SESSION['foo']))
{
$foo = $_SESSION['foo'];
}
else
{
// Hasn't been initialized, so do so now.
$foo = new Foo();
$_SESSION['foo'] = $foo;
}
?>
I'd be careful about storing objects in session data in this way, though, as it's opposed to the statelessness of the HTTP protocol. It's probably best to store a minimum of information in the session from which the state of the application can be reconstructed. For example, you might store just the ID of the currently logged in user, rather than the whole object, and then re-initialize it from that ID on each request. As mentioned in the comments, any object that you want to persist in this way must also implement the __sleep
and __wakeup
methods.
It's probably worth reading some of the discussion on this question, too.