Perhaps a somewhat weird question, but I want to know if there is any way to carry over class properties and set variables without re-instantiating it on all the pages that need it. For example, let's say I have the class "user" which does 3 things:
- Logs the user in
- Checks if user / logged in session is valid (applied to cer开发者_开发百科tain "protected" areas)
- Logs a user out if desired
Now, on the login page I instantiate the class, user submits a form, username and password are captured as POST variables, assigned to variables within the class, and the login function is called. All database work is done, sessions are set, and if successful the user is redirected to page 'x'
Now, on page 'x' I need to check if the users logged in session is valid, and this makes use of a function inside my class called isUserValid()
Is there no way I can "carry" the instantiated class over and call that function based on the original entered values? At the moment a new instance of the user class is being called on each page where a check is desired, and so the username and login tokens are stored in session variables to use in the newly assigned class instance.
I hope there's a way to use the first (and hopefully only) instance of the class that we made on the login home page.
Kind regards, Simon
you could make the method static so it would be called by User::isUserValid() and do the checks in there...
PHP doesn't have state between requests other than using sessions (or some other data source)
If you need to carry it over between requests, you need to store it somewhere and reload it again on the next pae.
I think what you're looking for is spl_autoload_register.
It allows you to call any class automatically without having to include the class file. It includes class files on-the-fly. Only file you include is the autoload.php file. Of course you still need to reference the class by $var = new Class() but it saves a lot of hassle nonetheless!
精彩评论