错误:调用非对象上的成员函数

时间:2012-12-02 15:41:28

标签: php ajax

我正在尝试在服务器上为我正在创建的游戏设置一个计时器,但我一直在“非对象”错误上“调用成员函数stop()。”

为了开始时间,我进行以下ajax调用

$.post('game.php', {
    action: 'start'
}, function(res) {
},'json');

当游戏结束时,我尝试通过进行以下ajax调用来停止计时器

$.post('game.php', {
    action: 'stop'
}, function(res) {
},'json');

game.php代码是

$action = $_POST['action'];

switch($action) {
case 'start':
    $gameTime = new timer();
    $gameTime->start();
    break;
case 'stop':
    $gameTime->stop();
    break;
}

class Timer {

   var $classname = "Timer";
   var $start     = 0;
   var $stop      = 0;
   var $elapsed   = 0;

   # Constructor
   function Timer( $start = true ) {
      if ( $start )
         $this->start();
   }

   # Start counting time
   function start() {
      $this->start = $this->_gettime();
   }

   # Stop counting time
   function stop() {
      $this->stop    = $this->_gettime();
      $this->elapsed = $this->_compute();
   }

   # Get Elapsed Time
   function elapsed() {
      if ( !$elapsed )
         $this->stop();

      return $this->elapsed;
   }

   # Get Elapsed Time
   function reset() {
      $this->start   = 0;
      $this->stop    = 0;
      $this->elapsed = 0;
   }

   #### PRIVATE METHODS ####

   # Get Current Time
   function _gettime() {
      $mtime = microtime();
      $mtime = explode( " ", $mtime );
      return $mtime[1] + $mtime[0];
   }

   # Compute elapsed time
   function _compute() {
      return $this->stop - $this->start;
   }
}

当我拨打电话停止计时器时,我收到错误。 我试图找出什么是错的,我想知道是不是因为我正在进行ajax调用?

有没有人知道如何让这个工作?

2 个答案:

答案 0 :(得分:1)

这个

switch($action) {
case 'start':
    $gameTime = new timer();
    $gameTime->start();
    break;
case 'stop':
                   <-----there should be  $gameTime = new timer();
    $gameTime->stop();
    break;
}

应该是

 switch($action) {
    case 'start':
        $gameTime = new timer();
        $gameTime->start();
        break;
    case 'stop':
     $gameTime = new timer();
        $gameTime->stop();
        break;

}

或尝试

  $gameTime = new timer();
      switch($action) {
    case 'start':

        $gameTime->start();
        break;
    case 'stop':

        $gameTime->stop();
        break;

}

答案 1 :(得分:0)

在你的停止案例中,你必须像在开始案例中那样初始化计时器。