PHP OOP에서 static 사용 예시

다음과 같은 User 클래스가 있다고 가정해 보겠습니다:

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

이 클래스가 자신의 객체 수를 계산하도록 만들어 봅시다. 이를 위해 정적 속성 count를 만듭니다. 초기값으로 0을 할당하고, 새로운 객체가 생성될 때마다 이 값을 1씩 증가시킵니다.

객체의 생성자에서 카운터 값을 증가시킬 것입니다:

User.php<?php
  class User
  {
    public static $count = 0; // 객체 카운터
    public $name;
    
    public function __construct($name)
    {
      $this->name = $name;
      
      // 객체 생성 시 카운터 증가:
      self::$count++;
    }
  }
?>

모든 것이 제대로 작동하는지 확인해 봅시다:

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

카운터를 비공개로 만드세요. 그 값을 특별한 메서드를 통해서만 얻을 수 있도록 하세요.