OOP နှင့် PHP တွင် static အသုံးပြုပုံ နမူနာ

ကျွန်ုပ်တို့တွင် အောက်ပါအတိုင်း <User> class တစ်ခုရှိသည်ဆိုပါစို့။

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

ဤ class သည် ၎င်း၏ object မည်မျှရှိသည်ကို ရေတွက်နိုင်ရန် ပြုလုပ်ကြပါစို့။ ထိုသို့ပြုလုပ်ရန် static property <count> ကို ဖန်တီးပါမည်။ အစတွင် ၎င်းအတွင်း <0> တန်ဖိုးကို သတ်မှတ်ပြီး object အသစ်တစ်ခုစီ ဖန်တီးတိုင်း ၎င်းတန်ဖိုးကို <1> တိုးမြှင့်ပေးပါမည်။

ကျွန်ုပ်တို့၏ counter ၏ တန်ဖိုးကို object ၏ constructor အတွင်း၌ တိုးမြှင့်ပါမည်။

User.php<?php
  class User
  {
    public static $count = 0; // object များအတွက် counter
    public $name;
    
    public function __construct($name)
    {
      $this->name = $name;
      
      // Object ဖန်တီးချိန်တွင် counter ကို တိုးမြှင့်ပါ။
      self::$count++;
    }
  }
?>

အားလုံး အလုပ်လုပ်မလုပ်ကို စစ်ဆေးကြည့်ပါမည်။

index.php<?php
  $user1 = new User('user1');
  echo User::$count; // 1 ကို ပြသမည်
  
  $user2 = new User('user2');
  echo User::$count; // 2 ကို ပြသမည်
?>
Задание 1

�ျွန်ုပ်တို့၏ counter ကို private အဖြစ် ပြုလုပ်ပါ။ �င်း၏တန်ဖိုးကို အထူး method တစ်ခုကို အသုံးပြု၍ ရယူနိုင်ပါစေ။