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


How to use Normal Variable inside Static Method

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

是否可以将全局变量用于静态数学?

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

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

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

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

首先,变量需要是静态的,因为您要使用此变量的方法就是静态方法

其次,在引用类时需要使用 self:: 而不是 $this->