Main Content

Static class members in PHP - a documented example

Archive - Originally posted on "The Horse's Mouth" - 2010-03-16 07:11:24 - Graham Ellis

Within a class, you can have dynamic or object variables and methods, where the code and the values associated with it are applied to individual objects. They're far and away the majority of your variables / methods - in yesterday's public transport service exercise, each train or bus had a potentially different start time, for example.

But just occasionally, you need a static or class variable or method, which applies to the class as a whole.

In PHP, you can define a static variable within your class using the static keyword (and you should initialise it as you do so):

  static $id_service = 0;

You can then reference that variable within both static and dynamic methodsusing the notation self::...:

  self::$id_service++;

You can define static or class functions too, but they can only access static variables - they do NOT have any $this-> access:

  static function next_id() {
    return self::$id_service + 1;
  }

Within the calling code, you access the static method using the notation class::method:

  print ("The next service will have id ". service::next_id() ."\n");

There is a complete example [here] from which the above lines of code have been "Cherry Picked"

When should you use static members?

Very rarely indeed!! There's a great temptation to use them to hold a count of the number of objects you have of a type, but that approach can fall over on you if you want to create a number of different groups - you should hold them in arrays and count the arrays if that's what you need to do.

My example for this post uses a static variable to assign a unique ascending ID number to each object of a type; that's subtley different, and a good use of statics.