Error while Storing Object Variables as Session Variables.

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
joeann
Forum Newbie
Posts: 1
Joined: Mon Nov 14, 2005 12:01 am

Error while Storing Object Variables as Session Variables.

Post by joeann »

I am a beginner in PHP programming. I was trying to store object variables as session variables, so that we don't have to create an object every time the page loads.

I have a simple class file simple.php

Code: Select all

<?php
class simple{ 
  function dummy(){ 
   print "TEST SUCCESSFUL!\n"; 
  } 
} 
?>
Then I created a simple .php which starts a new session and registers the object-variable of the class.

// test1.php

Code: Select all

<?php
require ("simple.php"); 
session_start(); 
$CLSOBJ=new simple();
session_register("CLASSOBJ"); 
$CLASSOBJ=$CLSOBJ; 
print isSet($_SESSION['CLASSOBJ']);
$CLASSOBJ->dummy();
?>
This file works fine and it prints the required result.

In the other .php files I have added the following lines:

Eg:// test2.php

Code: Select all

<?php
require("simple.php"); 
session_start(); 
print isSet($_SESSION['CLASSOBJ']);
$CLASSOBJ->dummy(); 
?>
Here in test2.php the session variable is active. So, it outputs "1" for
'print isSet($_SESSION['CLASSOBJ']);'
but a fatal error like 'Call to a member function on a non-object in' is coming for '$CLASSOBJ->dummy();' . Any idea?Or any alternate method to this?Pls help....


Hawleyjr: Please Use PHP Tags
viewtopic.php?t=21171
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Persisting objects through requests using SESSIONS is not a good idea: SESSIONS are bound to specific users, so the object will only get persisted when the same user pops in.

Generally, objects aren't that expensive to instantiate, so there should be no problem instantiating them on the fly.

If you want to assign variables to a session, use $_SESSION['varname'] = $var. For storing objects, check out serialize().

The fatal error is caused by the fact that the object itself doesn't exist.

Use PHP tags when posting.

Edit - W00t! 900 posts!
Post Reply