'How to use Normal Variable inside Static Method

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

Exam::increaseFoo();

This code generate an Error

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

Is that possible to use global variable into static mathod?

php


Solution 1:[1]

replace $this with self, also you must mark your variable as static when using it in a static method:

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

Exam::increaseFoo();

Solution 2:[2]

Variable inside class has to be static. No need to declare the variable as public.

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

Exam::increaseFoo();

Solution 3:[3]

Firstly, Variable needs to be static as the method where you want to use this variable is static method

Secondly, need to use self:: instead of $this-> while refferencing the class

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Mahmud Haisan