Introduction

You can create static class properties by adding the static keyword just before the property name:

class MyClass {
          public static $myProperty;
}

Static members of a class are independent of any particular object derived from that class.

To access a static property, you write the class name, followed by two colons (::), followed by the property name preceded by a $ symbol:

Here's an example using the Truck class:

Demo

<?php
class Truck {/*from ww w. j  a va2s  . co m*/
          public $color;
          public $manufacturer;
          static public $numberSold = 123;
}

Truck::$numberSold++;
echo Truck::$numberSold; // Displays"124"
?>

Result

Within the Truck class, a static property, $numberSold, is declared and also initialized to 123.

Then, outside the class definition, the static property is incremented and its new value, 124, is displayed.

Static properties are useful when you want to record a persistent value that's relevant to a particular class, but that isn't related to specific objects.

Related Topic