在不同用户之间共享PHP单例对象

时间:2014-10-29 17:17:43

标签: php singleton

我正在开发一个Web应用程序,允许用户登录并提供管理员安排的考试。我有一个"积累"所有用户完成测试并更新数据库后,应该自动运行的功能(根据某些逻辑)。

我知道我可以使用数据库来保存现在正在进行测试的用户的存储并相应地运行逻辑,但我有兴趣知道是否可以通过单例类来完成。

我的代码:

class ScoreBoard{
  var $current;
  private static $board=NULL;
  // private static $current=0;
  private function __construct() {
    $this->current=0;
  }
  static function scoreboard(){
    if(!self::$board){
        self::$board= new ScoreBoard();
        $this->log("Created new");
        // return self::$board;
    }
    return self::$board;
  }
  function add(){
    $this->current+=1;
    $this->log("add ".$this->current);
  }
  function subtract(){
    $this->current-=1;
    $this->log("subtract ".$this->current);

    // file_put_contents("scoreboard.txt",self::$current);
    if($this->current<0)
        $this->current=0;
    if($this->current<=0)
        {
            $this->accumulate();
            self::$board=NULL;
        }
  }
}

startExam.php文件中,我将此函数称为:

$scoreboard= ScoreBoard::scoreboard();
$scoreboard->add();

正在做

$scoreboard= ScoreBoard::scoreboard();
$scoreboard->subtract();

考试结束时。因此,当每个用户开始检查时,应该调用单个对象add函数,当他结束它时,应该调用subtract函数。但由于某些原因,这似乎不起作用,$current从未增加到超过1。

如果我想要做的事情是否有可能,请告诉我。如果有更好的方法来实现我想做的事。谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用Memcached来实现此目标 -

你的构造函数看起来像这样:

$this->memcache = new Memcached(); 
$this->memcache->addServer("127.0.0.1", "11211") // I think that's the right port for default.
$this->current = $this->memcache->get("current"); 

但是你可以通过将值存储在文件中来实现相同的逻辑 - 这会更容易......

相关问题