⊗ppOpStMIC 45 of 107 menu

Static Methods Inside a Class in OOP in PHP

If you want to use static methods inside a class, you should access them not via $this->, but with the help of self::.

As an example, let's add to our Math class a method getDoubleSum, which will find the doubled sum of numbers. We will use the already existing method getSum inside the new method:

<?php class Math { // Find the doubled sum: public static function getDoubleSum($a, $b) { return 2 * self::getSum($a, $b); // use another method } public static function getSum($a, $b) { return $a + $b; } public static function getProduct($a, $b) { return $a * $b; } } ?>

Let's use the new method:

<?php echo Math::getDoubleSum(1, 2); ?>

Convert the methods of the following class to static:

<?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; } } ?>
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline