Statiese metodes binne 'n klas in OOP in PHP

As jy statiese metodes binne 'n klas wil gebruik, moet jy na hulle verwys nie met $this-> nie, maar met behulp van self::.

Byvoorbeeld, laat ons byvoeg by ons klas Math 'n metode getDoubleSum wat sal dubbel die som van getalle vind. Laat ons gebruik binne die nuwe metode die reeds bestaande metode getSum:

Math.php<?php
  class Math
  {
    // Laat ons dubbel die som vind:
    public static function getDoubleSum($a, $b)
    {
      return 2 * self::getSum($a, $b); // gebruik 'n ander metode
    }
    
    public static function getSum($a, $b)
    {
      return $a + $b;
    }
    
    public static function getProduct($a, $b)
    {
      return $a * $b;
    }
  }
?>

Laat ons die nuwe metode gebruik:

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

Verander die volgende klas se metodes na staties:

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;
    }
  }
?>