Page 1 of 1

Error while Storing Object Variables as Session Variables.

Posted: Mon Nov 14, 2005 3:12 am
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

Posted: Mon Nov 14, 2005 3:08 pm
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!