PHP OOP တွင် Traits

သင်သိပြီးဖြစ်သည့်အတိုင်း PHP တွင် class တစ်ခုတည်းမှသာ မဟုတ်ဘဲ class များစွာမှ တစ်ပြိုင်နက် အမွေဆက်ခံ၍မရပါ။ ယခင်က ဤပြဿနာအတွက် ဖြေရှင်းနည်းကို ကျွန်ုပ်တို့ လေ့လာခဲ့ပြီးဖြစ်သည်- အမွေဆက်ခံခြင်းအစား class တစ်ခုအတွင်း အခြား class များ၏ object များကို အသုံးပြုရန်။

PHP တွင် အခြားနည်းလမ်းတစ်ခုလည်း ရှိပါသည်။ ၎င်းသည် traits များကို အသုံးပြုခြင်းပေါ် အခြေခံပါသည်။ Trait တစ်ခုသည် property များနှင့် method များ၏ အစုတစ်ခုကို ကိုယ်စားပြုပြီး အခြား class များအတွင်းသို့ ထည့်သွင်းနိုင်ပါသည်။ ဤသို့ဖြင့် trait ၏ property များနှင့် method များကို class မှ ၎င်း၏ကိုယ်ပိုင် property နှင့် method များကဲ့သို့ သတ်မှတ်မည်ဖြစ်သည်။

Trait ၏ syntax သည် class နှင့် အတူတူပင်ဖြစ်ပြီး trait အမည်ကို trait ဟူသော keyword ဖြင့် ကြေညာရမည်ဆိုသည့် အချက်ကိုလွဲ၍ အတူတူပင်ဖြစ်သည်။

Trait ၏ instance ကို ဖန်တီး၍မရပါ - traits များသည် အခြား class များသို့ တွဲဖက်ရန်အတွက်သာ ရည်ရွယ်ပါသည်။ တွဲဖက်ခြင်းကိုယ်တိုင်ကို use command ဖြင့် လုပ်ဆောင်ပြီး ၎င်းနောက်တွင် နေရာလပ်ခြားကာ တွဲဖက်လိုသော trait ၏အမည်ကို ဖော်ပြရပါမည်။ ဤ command ကို class ၏အစတွင် ရေးသားရပါမည်။

လက်တွေ့ဥပမာတစ်ခုဖြင့် traits များ၏အသုံးပြုပုံကို ကြည့်ရှုကြပါစို့။ ကျွန်ုပ်တို့တွင် name နှင့် age ဟူသော private property များနှင့် ၎င်းတို့၏ getter များပါဝင်သည့် Helper ဟူသော trait တစ်ခု ရှိသည်ဆိုပါစို့-

Helper.php<?php
  trait Helper
  {
    private $name;
    private $age;
    
    public function getName()
    {
      return $this->name;
    }
    
    public function getAge()
    {
      return $this->age;
    }
  }
?>

ထို့အပြင် ကျွန်ုပ်တို့တွင် ၎င်း၏ constructor အတွင်း၌ name နှင့် age property များ သတ်မှတ်ထားသည့် User ဟူသော class တစ်ခုလည်း ရှိသည်ဆိုပါစို့-

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

ယခု ကျွန်ုပ်တို့၏ User class အတွက် property များ၏ getter များကို ထည့်သွင်းကြပါစို့။ သို့ရာတွင် ၎င်းတို့ကို class အတွင်း၌ပင် ရေးသားမည်မဟုတ်ဘဲ ဤ method များကို အကောင်အထည်ဖော်ပြီးဖြစ်သည့် Helper trait ကို ရှင်းလင်းစွာ တွဲဖက်လိုက်ပါမည်-

User.php<?php
  class User
  {
    use Helper; // trait ကို တွဲဖက်ပါ။
    
    public function __construct($name, $age)
    {
      $this->name = $name;
      $this->age = $age;
    }
  }
?>

Trait ကို တွဲဖက်ပြီးနောက် ကျွန်ုပ်တို့၏ class အတွင်း ၎င်း trait ၏ method များနှင့် property များ ပေါ်လာပါလိမ့်မည်။ ဤသို့ဖြင့် ၎င်းတို့ကို class ၏ method များနှင့် property များကဲ့သို့ပင် ရည်ညွှန်းအသုံးပြုနိုင်ပါမည်-

index.php<?php
  $user = new User('john', 30);
  echo $user->getName(); // 'john' ကို ပြသမည်။
  echo $user->getAge();  // 30 ကို ပြသမည်။
?>
Задание 1

name, age, population property များနှင့် ၎င်းတို့၏ getter များပါဝင်သည့် City class ကို အကောင်အထည်ဖော်ပါ။ ကျွန်ုပ်တို့၏ class သည် ၎င်း၏ code ကို ချုံ့ရန်အတွက် ကျွန်ုပ်တို့ ဖန်တီးပြီးဖြစ်သည့် Helper trait ကို အသုံးပြုပါစေ။