如何在静态方法中使用正常变量

时间:2016-03-10 10:48:22

标签: php

class Exam {
  public $foo = 1;
  public static function increaseFoo(){
    $this->foo++;
    echo $this->foo;
  }
}

Exam::increaseFoo();

此代码生成错误

E_ERROR : type 1 -- Using $this when not in object context -- at line 5

可以将全局变量用于静态mathod吗?

2 个答案:

答案 0 :(得分:0)

$this替换为self,在静态方法中使用变量时,必须将变量标记为静态:

class Exam {
  public static $foo = 1;
  public static function increaseFoo(){
    self::$foo++;
    echo self::$foo;
  }
}

Exam::increaseFoo();

答案 1 :(得分:0)

类中的变量必须是静态的。无需将变量声明为public。

class Exam {
  private static $foo = 1;
  public static function increaseFoo(){
      self::$foo++;
      echo self::$foo;
  }
}

Exam::increaseFoo();