Statičke metode unutar klase u OOP u PHP-u
Ako želite da koristite statičke metode
unutar klase, onda im treba pristupiti
ne preko $this->, već uz pomoć
self::.
Na primer, dodajmo u našu klasu Math
metod getDoubleSum, koji će
pronalaziti duplirani zbir brojeva. Upotrebićemo
unutar novog metoda već postojeći metod
getSum:
<?php
class Math
{
// Pronađimo duplirani zbir:
public static function getDoubleSum($a, $b)
{
return 2 * self::getSum($a, $b); // koristimo drugi metod
}
public static function getSum($a, $b)
{
return $a + $b;
}
public static function getProduct($a, $b)
{
return $a * $b;
}
}
?>
Upotrebimo novi metod:
<?php
echo Math::getDoubleSum(1, 2);
?>
Preoblikujte metode sledeće klase u statičke:
<?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;
}
}
?>