Jump to content

Static Method and Sessions


Gogeta195

Recommended Posts

Problem is, I'm trying to track how many people are logged in using static variables. This works fine if I create LoggedUser objects on the same page as the LoggedUser::getCount() is called. But session variables as shown in the below code doesn't track the logged in users. How do I write my code so that Session variables can be used to this effect?

[code]
//class_LoggedUser.php
<?php
class LoggedUser
{
private static $count = 0;          // Keeps count of all users who are logged in

public function __construct()        // Constructor
{
  self::$count++;            // Increment the count
}

public function __destruct()        // Destructor
{
  self::$count--;            // Decrement the count
}

public static function getCount()        // Return the count of all logged in users
{
  return self::$count;          // Return the count
}
}
?>

// some other page getting called by many users
<?php
session_start();
$_SESSION['LoggedUser'] = new LoggedUser();
?>

// test.php
<?php
session_start();
$count = LoggedUser::getCount();        // get the static count of all users logged in
$sysinfo = "Number of Users Currently Logged In: $count<br/>";
print($sysinfo);
?>
[/code]
Link to comment
https://forums.phpfreaks.com/topic/31686-static-method-and-sessions/
Share on other sites

Static member data in PHP does not work in the same way that it does it other languages.  The PHP environment is newly created for each HTTP request. This means that under oridnary circumstances static data can not exist across multiple requests.  When using sessions you can force the static data to persist for one user across multiple HTTP requests by means of writing state data to the server's disk but this is still not accomplish what you want.  In order to maintain some sort of state across multiple users and multiple HTTP requests you will require some kind of persistant medium i.e., a database, flat file etc.

Your class could be easily modified to maintain state in a database or flat file.  I hope this helps.

Best,

Patrick

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.