PHP OOP တွင် Class အတွင်း Static Methods များ

အကယ်၍ class အတွင်းရှိ static methods များကို အသုံးပြုလိုပါက၊ $this-> ဖြင့် မခေါ်သင့်ပါ။ ယင်းအစား self:: ကို အသုံးပြုရပါမည်။

ဥပမာအနေဖြင့် ကျွန်ုပ်တို့၏ Math class ထဲသို့ getDoubleSum method တစ်ခု ထည့်ကြည့်ပါမည်။ ၎င်းသည် ကိန်းများ၏ နှစ်ဆပေါင်းလဒ်ကို ရှာပေးပါမည်။ ထို method အသစ်အတွင်း၌ ရှိပြီးသား getSum method ကို သုံးကြည့်ပါမည်။

Math.php<?php
  class Math
  {
    // နှစ်ဆပေါင်းလဒ်ကို ရှာကြည့်ပါမည်။
    public static function getDoubleSum($a, $b)
    {
      return 2 * self::getSum($a, $b); // အခြား method ကို သုံးပါမည်။
    }
    
    public static function getSum($a, $b)
    {
      return $a + $b;
    }
    
    public static function getProduct($a, $b)
    {
      return $a * $b;
    }
  }
?>

Method အသစ်ကို အသုံးပြုကြည့်ပါမည်။

index.php<?php
  echo Math::getDoubleSum(1, 2);
?>
Задание 1

အောက်ပါ class ၏ methods အားလုံးကို static methods အဖြစ် ပြန်လည်ပြင်ဆင်ပါ။

ArraySumHelper.php<?php
  class ArraySumHelper
  {
    public function getSum1($arr)
    {
      return $this->getSum($arr, 1);
    }
    
    public function getSum2($arr)
    {
      return $this->getSum($arr, 2);
    }
    
    public function getSum3($arr)
    {
      return $this->getSum($arr, 3);
    }
    
    public function getSum4($arr)
    {
      return $this->getSum($arr, 4);
    }
    
    private function getSum($arr, $power) {
      $sum = 0;
      
      foreach ($arr as $elem) {
        $sum += pow($elem, $power);
      }
      
      return $sum;
    }
  }
?>