Page 1 of 1

read/write Session Variables from a class

Posted: Wed Aug 08, 2012 10:41 am
by IGGt
I have created a class to handle some Debugging code, but I am stuck at how to make it read / write to a Session Variable.

I have a $Counter variable that normally holds an incrementing Page Counter, which is then stored to a SESSION Variable between page loads.

But I can't see how to do it in a class. I was thinking something like:

Code: Select all

class pgCounter
{
		var $timezone;
		var $date;
		var $DebugDate;
		var $ResetTime;
		
		var $Counter;
		
		function __construct()
		{
			$this->timezone = "Europe/London";
			date_default_timezone_set ($this->timezone);
			$this->date = date('H:i:s');
		}
		
		function Counter()
			{
				echo $this->date;
				if(isset($_SESSION['Counter']))
					{
						$Counter = $_SESSION['Counter'];
					}
				else
					{
						$Counter = 1;
					};
				$_SESSION['Counter'] = $Counter;
				
				echo "Count - $this.Counter;
								
				$this->Counter++;
				$_SESSION['Counter'] = $this->Counter;
			}
}
but it doesn't work, what is the correct way to read / write Session variables from classes?

Re: read/write Session Variables from a class

Posted: Wed Aug 08, 2012 1:03 pm
by Christopher
That should work, but the session is probably not started. Maybe create a session class that auto-starts the session and inject it into your pgCounter class.

Re: read/write Session Variables from a class

Posted: Thu Aug 09, 2012 2:19 am
by IGGt
Spot on, I forgot that because I was working on a 'test' page, it wasn't going to run under the same Session as my Live page, So I just started a new Session on there and it's fine.

cheers