How to create static properties and methods

A class with a private static property and a public static method

class Category {
  private $id, $name;
  private static $objectCount = 0; // declare a static property
  public function __construct($id, $name) {
    $this->id = $id;
    $this->name = $name;
    self::$objectCount++; // update the static property
  }
  
  // A public method that gets the static property
  public static function getObjectCount(){
    return self::$objectCount;
  }

  // The rest of the methods for the Category class
}

How to use a public static method from outside a class

$guitars = new Category(1, 'Guitars');
$basses = new Category(2, 'Basses');
echo("<p> Object count: " . Category::getObjectCount() . "</p>); // 2 
$drums = new Category(3, 'Drums');
echo("<p> Object count: " . Category::getObjectCount() . "</p>); // 3

How to use a public static property from outside a class

echo("<p> Object count: $objectCount</p>);

Description

Back