Introduction to PHP – Static Variables

Guest Posts Paolo Nikko Nuñal

What are static variables? You might have encountered them when you are doing object oriented programming. But have you asked yourself what are they used for?

Static variables from the name itself 'static' meaning that they don't change or lacks in action. In PHP or Java the 'static' keyword is a reserve word that is use to create static variables.

For example.

Syntax:

<?php
   class Pinball{
      static $highscore = 0;
   }
?>


Base from the example above, we have declared a new  static variable called $highscore in which it is assigned with a value with zero. From the class itself, you already have an idea that we have created a game called Pinball and that a game has a highscore. Everytime you create a new Pinball game, each game always has a 'score' for that particular instance or session played by a player and at the same time will always store the highscore considering the fact that it is still the same game that they are playing and that is Pinball.

<?php
   class Pinball{
      public static $highscore = 0;

      public __construct(){
          echo "new pinball game created";
      }
      public setScore($highscore){
          if($this::$highscore < $highscore)
          {
            $this::highscore= $highscore;
          }
      }
   }

   $game1 = new Pinball();
   $game2 = new Pinball();
   $game3 = new Pinball();
   $game1->setScore(100);
   $game2->setScore(500);
   $game3->setScore(200);

   echo "<br>".$game1::$highscore;
   echo "<br>".$game2::$highscore;
   echo "<br>".$game3::$highscore;
?>


The following result will yield the number 500 since it is the highest score. And everytime you create an instance of the Pinball class, it will automatically share what value of the highscore it currently has.