tags:

views:

335

answers:

2

hi guys,

how to do this using PHP OOP to maintain object state in different pages.

the problem is im always instantiate the object on every page.

is there a solution that i instantiate it once and maintain its object on different pages.

Thanks in advance

+8  A: 

In PHP pretty much everything is instantiated on every page hit. If you want to maintain state you have a number of choices:

  1. For user-specific data you can put it in a cookie (not recommended for security reasons);
  2. Put user-specific data in the session, which basically means writing it to file and loading it from file on every hit;
  3. Storing it in some form of persistent storage, such as a file or database table;
  4. Store it in a cache of some kind (eg memcached).

Which one you use depends on factors such as if the data is global, user-specific, etc and a number of other factors (such as how often it is read, how often it is written, etc).

So it's impossible to give you a definitive answer as the nature of what you want to be persistent is unclear. If you're worried about the cost of creating an object then, unless it is really expensive, don't. Don't optimize a problem until you have a problem.

cletus
Excellent answer, couldn't have put it better. #4 is probably preferred with sync back to the main DB after changes.
Artem Russakovskii
To elaborate on #2, which I suspect is exactly what you're looking for, the file writing and loading operations are done automatically by PHP, you just call session_start() and read/set values in the $_SESSION array. It is still worth remembering though that session data is written to a file on the back end, which is why it may be more desirable after a point to use a database solution instead.
dimo414
+1  A: 

You can also look at Object serialization. You will find more information here. http://uk.php.net/serialize. This will convert your object into a format that can be used to store into session data. Once your data is stored in sessions, you can then read the data on the next user page load and unserialize the data to get back your object!

Here is a good article which shows how serialization will allow your object to be used across two different PHP pages. http://www.phpbuilder.com/manual/en/language.oop.serialization.php

Webber