Jump to content

passing object reference to a session


n3p3

Recommended Posts

When an object reference is passed to the $_SESSION, what happens to the object?

For ex, in login system,

user first enters the username and password, (assuming its correct) defining the session variable as a reference to the database object like $_SESSION["db_cnn"]=&new DB(...);

and accessing to db object as $_SESSION["db_cnn"]->Query(...) in other pages...

 

is it an optimized way to use sessions in this purpose? can it be implemented to the MVC pattern? What are the advantages, and disadvantages?

 

Thank you

Link to comment
Share on other sites

actually it works..a simple example (referencing the example in php.net/autoload),

 

autoload.php

<?php
function __autoload($class) {
  require_once("$class.php");
}
?>

 

sampleClass.php

<?php
class sampleClass {

  function __construct($value) {
    $this->dbvar = $value;
  }

  function getValue() {
    return $this->dbvar;
  }
}
?>

 

page1.php

<?php
require_once('autoload.php');
session_start();
$_SESSION['testObj'] = new sampleClass('localhost');
echo '<a href="page2.php">Go to page 2</a>';
?>

 

page2.php

<?php
require_once('autoload.php');
session_start();
echo $_SESSION['testObj']->getValue();
?>

 

But..When an object reference is passed to the $_SESSION, what happens to the object? If the object is still allocated in the memory, instead of creating a new object in page2.php, we can access the object by using object reference stored in our session variable..and I believe it will be a good optimization. Am I wrong?

Link to comment
Share on other sites

actually it works..a simple example (referencing the example in php.net/autoload),

 

No it doesn't, we're just not talking about the same thing. Objects can be serialized (thank god), resources can not.

 

And no, using the default php session handler objects put in session are not kept in memory. The session extension creates a string presentation of them and writes them to disk. Plenty of other possibilities, but all of them serialize (in php that by means flattening them to a string) the objects. Except for one option, but you don't want to go there.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.