Please help!! Is there a way to share object between page?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yalag
Forum Newbie
Posts: 3
Joined: Mon Apr 06, 2009 2:19 pm

Please help!! Is there a way to share object between page?

Post by yalag »

I am new to php, but in other web technologies, you can share objects between page instances. For example, in java jsp pages you easily have on class that exist as static class for the whole server instance. How to do this in php?

Thank you and appreciate your help!!
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Please help!! Is there a way to share object between page?

Post by Darhazer »

You can serialize the object in the session and retrieve it in the second page from the session

file1:

Code: Select all

 
session_start();
$myobj = new MyClass;
$_SESSION['myobj'] = $myobj;
 
file2:

Code: Select all

 
session_start();
// note: the definition of MyClass should be loaded before this line
// otherwise the object won't be deserialized
$myobj = $_SESSION['myobj'];
 
You can use the __sleep() and __wakeup() functions to predefine the serialization and deserialization.

Note: this is for all pages, but per user, not for all users. In JSP you have Application, which is shared between all users. To make this in PHP, you have to serialize the object in file or database, not in session, or to predefine the session handling, so you can use it across users
Post Reply