Jump to content

php & oop


otuatail

Recommended Posts

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
https://forums.phpfreaks.com/topic/198833-php-oop/#findComment-1043665
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
https://forums.phpfreaks.com/topic/198833-php-oop/#findComment-1043741
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.