read/write Session Variables from a class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

read/write Session Variables from a class

Post 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?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: read/write Session Variables from a class

Post 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.
(#10850)
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

Re: read/write Session Variables from a class

Post 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
Post Reply