Categories
PHP

PHP static methods

A static class in PHP acts pretty much the same way as static variables, it is loaded into the “static” space, where every time it is spawned or instantiated, it is the same object already built before.

Static variables inside classes can’t be addressed with the $this identifier:

class SomeClass {
   public static $counter = 0;
   function __construct() {
        self::$counter++; // Notice how we say self::$counter instead of $this->counter
   }
}
Creating a static method inside a class:
class SomeClass {
   public static function do() {
        // Code.
   }
}
So now, to call the method, we need to do the following:
SomeClass::do(); // $obj->do(); // NO!
Constants are like static variables, except that their values is final and can't be changed:
class SomeClass {
   const PI = 3.14;
}
To call the value:

$obj::PI; // $obj->PI // !No

 
Advantages / reasons for using static classes:

  1. Available anywhere from your script, without the need to instanciate an object or store it into a global variable.
  2. It can save you performance time, not instanciating objects just to access their static methods, functionality or variables.