PHP OOP တွင် object တစ်ခုဖန်တီးပြီးချင်း method ခေါ်ယူခြင်း

ကျွန်ုပ်တို့တွင် Arr class Arr ရှိသည်ဆိုပါစို့၊ ထို class သည် ဂဏန်းများကို array အဖြစ်သိမ်းဆည်းထားပြီး method getSum အသုံးပြု၍ ထိုဂဏန်းများ၏ ပေါင်းလဒ်ကို တွက်ချက်နိုင်သည်။ ဂဏန်းများကို object constructor သို့ array အဖြစ်ရောက်ရှိလာပြီး method add အသုံးပြု၍ တစ်ခုချင်းစီလည်း ထပ်မံထည့်သွင်းနိုင်သည်။

php<?php
  class Arr
  {
    private $numbers = [];
    
    public function __construct($numbers)
    {
      $this->numbers = $numbers;
    }
    
    public function add($number)
    {
      $this->numbers[] = $number;
    }
    
    public function getSum()
    {
      return array_sum($this->numbers);
    }
  }
?>

အောက်ပါသည် class Arr ၏ အသုံးပြုမှုနမူနာဖြစ်သည်။

php<?php
  $arr = new Arr([1, 2, 3]);
  
  $arr->add(4);
  $arr->add(5);
  
  echo $arr->getSum(); // ၁၅ ကို ဖော်ပြမည်
?>

ကျွန်ုပ်တို့သည် object ဖန်တီးချိန်တွင် လိုအပ်သောဂဏန်းအားလုံးကို ပေးပို့ပြီးနောက် ၎င်းတို့၏ပေါင်းလဒ်ကို ချက်ချင်းရှာဖွေလိုသည့် အခြေအနေမျိုးဖြစ်နိုင်သည်။

php<?php
  $arr = new Arr([1, 2, 3]);
  echo $arr->getSum(); // ၆ ကို ဖော်ပြမည်
?>

ကျွန်ုပ်တို့သည် object နှင့် နောက်ထပ်မည်သည့်လုပ်ဆောင်ချက်ကိုမျှ လုပ်ဆောင်ရန် မစီစဉ်ပါက အထက်ပါကုဒ်ကို ပိုတိုအောင်ရေးနိုင်သည်။ object တစ်ခုကိုဖန်တီးပြီး ၎င်း၏ method getSum ကို ချက်ချင်းခေါ်ယူနိုင်သည်။

php<?php
  echo (new Arr([1, 2, 3]))->getSum(); // ၆ ကို ဖော်ပြမည်
?>
Задание 1
php<?php
  class StringProcessor
  {
    private $str = '';
    
    public function __construct($text)
    {
      $this->str = $text;
    }
    
    public function append($text)
    {
      $this->str .= $text;
      return $this;
    }
    
    public function getValue()
    {
      return $this->str;
    }
    
    public function getLength()
    {
      return strlen($this->str);
    }
  }
?>

ဤ class ဖြင့် အောက်ပါအတိုင်း လုပ်ဆောင်ခဲ့သည်ဆိုပါစို့။

php<?php
  $str = new Str('aaa');
  $str->append('bbb');
  $str->append('ccc');
  
  echo $str->getLength();
?>

ဤကုဒ်ကို တိုက်ရိုက်ခေါ်ယူခြင်း (on the fly) မှတစ်ဆင့် ပြန်လည်ရေးပါ။