Jump to content

php & oop


otuatail

Recommended Posts

Hi. I have used classes and objects before in C++ but was wondering how I can use them in a web based php. The problem is they need to be persistant from page to page. Is there any way like using Session variables that this could be achieved.

 

TIA

 

Desmond.

 

Link to comment
Share on other sites

Or

 

class MyPersistingClass {
  public function __construct() {
    $this->restoreState();
  }
  
  public function __destruct() {
    $this->saveState();
  }
  
  private function saveState() {
    //add your fields to the $_SESSION variable
    //$_SESSION[get_class($this)] = array(..);
  }
  
  private function restoreState() {
    //retrieve values from the $_SESSION variable's into your fields
  }
}

 

It's generally not a good idea to store objects in sessions because:

 

1. Your class definition has to be present before session_start() is called

2. It takes longer for session_start() to rebuild the $_SESSION array using objects

 

There has been a discussion on this forums before on this topic and the suggested approach is storing array's.

Link to comment
Share on other sites

1. Your class definition has to be present before session_start() is called

 

That's what __autoload (or the spl equivalent) is for.  If you're serious about OOP in PHP, this isn't an issue.

 

2. It takes longer for session_start() to rebuild the $_SESSION array using objects

 

This is true.

 

There has been a discussion on this forums before on this topic and the suggested approach is storing array's.

 

I don't see anything wrong with storing objects in sessions if it's a small app.

 

To the OP, storing an array in sessions is the same as storing a single value.  Fill your array with your data, then assign it to a session variable.

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.