otuatail Posted April 17, 2010 Share Posted April 17, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/198833-php-oop/ Share on other sites More sharing options...
oni-kun Posted April 17, 2010 Share Posted April 17, 2010 serialize Quote Link to comment https://forums.phpfreaks.com/topic/198833-php-oop/#findComment-1043627 Share on other sites More sharing options...
ignace Posted April 17, 2010 Share Posted April 17, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/198833-php-oop/#findComment-1043665 Share on other sites More sharing options...
otuatail Posted April 17, 2010 Author Share Posted April 17, 2010 Ok thanks for this. The only problem is that I have only stored single values in a session. Necer stored an araay. How do I do this? Desmondd. Quote Link to comment https://forums.phpfreaks.com/topic/198833-php-oop/#findComment-1043675 Share on other sites More sharing options...
KevinM1 Posted April 17, 2010 Share Posted April 17, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/198833-php-oop/#findComment-1043741 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.