I knew it worked without manually un/serializing(), but it's news to me that you can define your class after the session_start()
Good to know!
Storing an object in a session
Moderator: General Moderators
- Kieran Huggins
- DevNet Master
- Posts: 3635
- Joined: Wed Dec 06, 2006 4:14 pm
- Location: Toronto, Canada
- Contact:
- aaronhall
- DevNet Resident
- Posts: 1040
- Joined: Tue Aug 13, 2002 5:10 pm
- Location: Back in Phoenix, missing the microbrews
- Contact:
If the class is designed to store only data you intend on saving (like state information), you're saving overhead by storing the object itself in the session. I'd do some microbenchmarks, but I'm sure that PHP will serialize/unserialize an object faster than it will extract and reassign each object property to a variable, serialize each variable, then undo the whole process. The extra steps save nothing, lose some cycles and add extra, unnecessary code.Jcart wrote:Well I think it is obvious that there will be overhead from having to persist objects in sessions and [s]serializing/unserializing[/s], but I would probably avoid its usage simply because it smells of a poor design. I would probably prefer storing the data and not the object itself in the session, then simply repopulate it on the next request.
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
I can think of several cases where I store objects in the session. Probably the most common with web applications is a Shopping Cart which is usually an object that contains one or more item objects.
It is news that you can now include the class after session_start() but before the object in the is used. It sounds like they may have moved the unserialize and object/class fixup from within session_start() to when the var is first accessed. It makes sense to lazy initialize because session vars are not necessarily used on every page that starts the session.
It is news that you can now include the class after session_start() but before the object in the is used. It sounds like they may have moved the unserialize and object/class fixup from within session_start() to when the var is first accessed. It makes sense to lazy initialize because session vars are not necessarily used on every page that starts the session.
(#10850)
That doesn't work for me.It is news that you can now include the class after session_start() but before the object in the is used.
Code: Select all
<?php
session_start();
if ( !isset($_SESSION['foo']) ) {
$_SESSION['foo'] = new Bar;
}
class Bar {
public $xyz;
}
print_r($_SESSION);
?>Code: Select all
<?php
session_start();
if ( !isset($_SESSION['foo']) ) {
$_SESSION['foo'] = new Bar;
}
if ( true ) {
class Bar {
public $xyz;
}
}
print_r($_SESSION);
?>- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US