Statické metody uvnitř třídy v OOP v PHP
Pokud chcete používat statické metody
uvnitř třídy, měli byste k nim přistupovat
nikoli přes $this->, ale pomocí
self::.
Jako příklad přidejme do naší třídy Math
metodu getDoubleSum, která bude
hledat zdvojený součet čísel. Použijeme
uvnitř nové metody již existující metodu
getSum:
<?php
class Math
{
// Najdeme zdvojený součet:
public static function getDoubleSum($a, $b)
{
return 2 * self::getSum($a, $b); // použijeme jinou metodu
}
public static function getSum($a, $b)
{
return $a + $b;
}
public static function getProduct($a, $b)
{
return $a * $b;
}
}
?>
Použijme novou metodu:
<?php
echo Math::getDoubleSum(1, 2);
?>
Přepracujte metody následující třídy na statické:
<?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;
}
}
?>