PHP OOP의 클래스 내부 정적 메서드

클래스 내부에서 정적 메서드를 사용하려면, $this->를 통해 접근하는 대신 self::를 사용해야 합니다.

예를 들어, Math 클래스에 숫자의 두 배 합계를 구하는 getDoubleSum 메서드를 추가해 보겠습니다. 새 메서드 내부에서 기존 메서드 getSum를 사용하겠습니다:

Math.php<?php
  class Math
  {
    // 두 배 합계를 구합니다:
    public static function getDoubleSum($a, $b)
    {
      return 2 * self::getSum($a, $b); // 다른 메서드를 사용합니다
    }
    
    public static function getSum($a, $b)
    {
      return $a + $b;
    }
    
    public static function getProduct($a, $b)
    {
      return $a * $b;
    }
  }
?>

새 메서드를 사용해 보겠습니다:

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

다음 클래스의 메서드를 정적 메서드로 수정하세요:

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