Using static properties and methods

PHP lets you access properties or methods without having to create an instance of the class. The keyword used for this purpose is static.

How to do it...

  1. At its simplest, simply add the static keyword after stating the visibility level when declaring an ordinary property or method. Use the self keyword to reference the property internally:
    class Test
    {
      public static $test = 'TEST';
      public static function getTest()
      {
        return self::$test;
      }
    }
  2. The self keyword will bind early, which will cause problems when accessing static information in child classes. If you absolutely need to access information from the child class, use the static keyword in place of self. This process is referred to as Late Static Binding.
  3. In the ...

Get PHP 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.