views:

180

answers:

5
+2  Q: 

PHP object keeping

Let's say that in my app I have an object instance created on page 1. The user then goes to some other part of app and I want the instance to remain. How can I 'save' the instance? Sessions?

A: 

There are two ways I have used for my applications: sessions and database.

Vladimir Kadalashvili
A: 

Sessions yes, but it will be a new instance with the same properties and not the same instance. Other options are using an O/R-Mapper to store the object in the DB and keep the key for it in the session, or use memcached with a unique key (say the session ID) - but this would still not be the same instance - just an instance with the same properties.

If you need the exact same instance of an object between two requests in PHP I'm afraid this is impossible (not impossible, everything is doable - but you'll have to run PHP on top of some type of application server)

thr
+5  A: 

Yes, use a session.

Call session_start() at the beginning of your page, then store your object with something like $_SESSION['myobject']=$myobject;

The later page can access $_SESSION['myobject'] after it too calls session_start()

You need to make sure that any page which uses that session has the class for the object defined or is capable of auto-loading it.

Your class can also define the magic methods __sleep and __wakeup which allow you to clean up any member variables you don't want serializing (like resources, such as db handles). During __wakeup you can restore these.

Paul Dixon
A: 

Thanks all of you! I'll try it ASAP :) also sorry for doublepost - I'm writing from my cellphone, and it seemed like this post didn't get posted.

Martin Janiczek
A: 

You fundamentally have two options: Server side state or client side state.

Server side state is usually done through sessions. This is the simplest and most powerful solution, but it has some drawbacks (Concurrency, unable to persist state over time, etc.).

Client side state can be maintained through the URL - Usually in query string parameters. For example, to "remember" a variable $name between two pages, you might create a link on the first page, like this: http://www.example.org/second_page.php?name=Jimbo, and the second page could then get the variable through $_GET. This is much harder to get right, and it has some limitations on how much state you can transfer between pages. For this reason, people have a tendency to go with server side state, even when client side state would be more appropriate.

troelskn