0

Possible Duplicate:
PHP: Storing 'objects' inside the $_SESSION

I have 2 scripts files named 'search.php' and 'share.php' and I want to send information from the first to the second one. I created a var named $_SESSION['search'] wich is a object of the class Search, but I can't read the object in the second script file.

search.php

session_start();
$_SESSION['search'] = new Search($text);

(...)

share.php

session_start();
$itemList = $_SESSION['search']->getItemList(); // Error

Why? How can I pass info from one script to another in PHP?

Community
  • 1
  • 1
Jimmy
  • 873
  • 3
  • 12
  • 29
  • 1
    What does the error say??? ALWAYS bring the error in your question, please. PS. Perhaps share.php haven't included the Search class so you can use their methods. (include more code) – Alfabravo Feb 21 '12 at 12:27

3 Answers3

0

If you are going to pass the variable using sessions then you need to add the variable to the session in search.php like so:

$itemlist = new Search($text);
$_SESSION['search']         = $itemlist;

And then get the variable back out in share.php like so:

$itemlist = $_SESSION['search'];
echo $itemlist;

If you are having problems I would check "new Search($text);" on the first page and be sure that it is what you actually want stored to begin with.

Dev Newb
  • 565
  • 1
  • 6
  • 24
  • Thats what I'm doing in '$_SESSION['search'] = new Search($text);' – Jimmy Feb 21 '12 at 12:26
  • So what problem are you running into? If you echo $itemlist on share.php what do you get? – Dev Newb Feb 21 '12 at 12:27
  • I get an error in php_error.log -> PHP Fatal error: Call to a member function getItemList() on a non-object in /Applications/MAMP/htdocs/SAPP2/share.php – Jimmy Feb 21 '12 at 12:49
0

PHP automagically serializes objects in a session.

You CANNOT have any members in that object that are resources (ie a db connection etc.). If you need them in there you need to add __sleep and __wake methods to the object you wish to store in the session. __sleep renders the obj as a value obj (an array actually as you must return an array) and the __wake method should reconstruct the obj based on that array.

read this

Ian Wood
  • 6,515
  • 5
  • 34
  • 73
0

Maybe you are only missing an include of your php file containing the Search class.

require_once('Search.php');

If the class is not known at the moment you deserialize the object from the session, then PHP makes a "dummy" object, only containing the attributes, but without knowledge about it's methods. If you include the class, then PHP can deserialize it to a real object of this class.

martinstoeckli
  • 23,430
  • 6
  • 56
  • 87