Statyczne metody wewnątrz klasy w OOP w PHP

Jeśli chcesz używać statycznych metod wewnątrz klasy, należy się do nich odwoływać nie przez $this->, ale za pomocą self::.

Dla przykładu dodajmy do naszej klasy Math metodę getDoubleSum, która będzie znajdować podwojoną sumę liczb. Użyjemy wewnątrz nowej metody już istniejącej metody getSum:

Math.php<?php
  class Math
  {
    // Znajdźmy podwojoną sumę:
    public static function getDoubleSum($a, $b)
    {
      return 2 * self::getSum($a, $b); // używamy innej metody
    }
    
    public static function getSum($a, $b)
    {
      return $a + $b;
    }
    
    public static function getProduct($a, $b)
    {
      return $a * $b;
    }
  }
?>

Skorzystajmy z nowej metody:

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

Przerób poniższe metody tej klasy na statyczne:

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