CodeCrack
CodeCrack

Reputation: 5363

Is there a way to pass an object through sessions and use its functions?

My understanding is that when you serialize an object and pass it through a session, for example, from index.php page to securePage.php, SESSION just passes that objects data, therefore, you can not use that object's functions. The only way is to create a new object on securePage.php with the data you have passed.... Is there a way to pass an actual object and then use it's functions without creating a brand new object on securePage.php.

Example:

$randomObj = new rndObject;
$_SESSION['object'] = serialize($randomObj);

and securePage.php

$whatever = unserialize($_SESSION['object']);

//below code won't work and say something like
//Fatal error: Call to a member function checkAccess() on a non-object in 
//securePage.php on line 39
echo $whatever->checkAccess();

Upvotes: 1

Views: 2293

Answers (2)

Shikiryu
Shikiryu

Reputation: 10219

You should use __sleep() and __wakeup() magic methods (that's what it's for) :

http://www.tuxradar.com/practicalphp/6/13/0

http://php.net/manual/en/language.oop5.magic.php

Upvotes: 0

cwallenpoole
cwallenpoole

Reputation: 82028

Sort of, to get the object which has been loaded into SESSION, you need to include the class definition somewhere before calling unserialize and it will work as you expect, but it will still, technically, create a new instance.

Upvotes: 3

Related Questions