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...
At its simplest, simply add the
static
keyword after stating the visibility level when declaring an ordinary property or method. Use theself
keyword to reference the property internally:class Test { public static $test = 'TEST'; public static function getTest() { return self::$test; } }
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 thestatic
keyword in place ofself
. This process is referred to as Late Static Binding.In the following example, if you echo
Child::getEarlyTest()
, the output will be TEST. If, on the other hand, you runChild::getLateTest()
, the output will be CHILD. The reason is that PHP will bind to the earliest definition when usingself
,...