Static properties and methods in PHP

We’ve seen how to define properties and methods that belong to the instance of a class, an object.

Sometimes it’s useful to assign those to the class itself.

When this happens we call them static and to reference or call them we don’t need to create an object from the class.

Let’s start with static properties, we define them with the static keyword:

class Utils {
  public static $version = '1.0';
}

We reference them from inside the class using the keyword self, which points to the class:

self::$version;

and from outside the class using:


Utils::version

This is what happens for static methods:

class Utils {
  public static function version() {
    return '1.0';
  }
}

From the outside of the class we can call them in this way:

Utils::version();

From inside the class, we can reference them using the self keyword, which refers to the current class:

self::version();

Download my free PHP Handbook!