Example of Static in OOP in PHP

Suppose we have the following class User:

User.php<?php
  class User
  {
    public $name;
    
    public function __construct($name)
    {
      $this->name = $name;
    }
  }
?>

Let's make it so that this class counts the number of its objects. To do this, let's create a static property count. Initially, we will set its value to 0, and when creating each new object, we will increase this value by 1.

We will increase the value of our counter in the object constructor:

User.php<?php
  class User
  {
    public static $count = 0; // object counter
    public $name;
    
    public function __construct($name)
    {
      $this->name = $name;
      
      // Increase the counter when creating an object:
      self::$count++;
    }
  }
?>

Let's check that everything works:

index.php<?php
  $user1 = new User('user1');
  echo User::$count; // will output 1
  
  $user2 = new User('user2');
  echo User::$count; // will output 2
?>
Задание 1

Make our counter private. Let its value be obtainable via a special method.