Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

maintain object state with different pages using PHP

Tags:

oop

php

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

like image 559
miss_viper Avatar asked Aug 09 '26 01:08

miss_viper


2 Answers

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.

like image 62
cletus Avatar answered Aug 10 '26 16:08

cletus


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

like image 26
Webber Avatar answered Aug 10 '26 15:08

Webber