/    Sign up×
Community /Pin to ProfileBookmark

storing object in session

i have an object that i want to save into the session.

my app is one page, using $_GET and $_POST to reload the page under different conditions, therefore using a temporary file to serialise/ unserialise is not preferable.

after scouring the net, i have come up with the following solution, placed at the top of my page:

[code=php]

include(“MyClass.php”);
session_start();

if(!isset($_SESSION[‘object’]))
{
//first time loaded, create new object and store in session
$MyObject = new MyClass;
$_SESSION[‘object’] = $MyObject;
}else{
//object already loaded
$MyObject = $_SESSION[‘object’];
}

[/code]

this will then work using the following notation:

[code=php]
$_SESSION[‘object’]->objProperty
[/code]

or

[code=php]
$_SESSION[‘object’]->objMethod()
[/code]

but i was wondering why i can’t use $MyObject->objProperty, which i specfiy in the else clause of the loop?

?

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@crh3675Apr 21.2004 — It may be becuase your initial $_SESSION variable only stores a reference. Then when you try to set it again, you are setting a reference to another reference. Not sure if that made sense or if that's the reason but I think that's why.

Try
<i>
</i>$MyObject = &amp;$_SESSION['object'];

print $MyObject-&gt;getProperty();
×

Success!

Help @moondance spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...