⊗ppOpAdCMS 17 of 107 menu

Class as a Set of Methods in OOP in PHP

Sometimes classes are used to group methods of similar topics. In this case, as a rule, only one object of this class is created and its methods are used many times in various situations.

Let's look at an example. Let's create a class that will manipulate arrays of numbers:

<?php class ArrHelper { } ?>

Each method of this class will take an array as a parameter and perform a specified operation on it. Let's say, for example, we have the following methods:

<?php class ArrHelper { public function getSum($arr) { // sum of elements } public function getAvg($arr) { // arithmetic mean } } ?>

Let's write the implementation of these methods:

<?php class ArrHelper { public function getSum($arr) { $res = 0; foreach ($arr as $num) { $res += $num; } return $res; } public function getAvg($arr) { $len = count($arr); if ($len > 0) { $sum = $this->getSum($arr); return $sum / $len; } else { return 0; } } } ?>

Let's see how we will use these methods. Let's create an object of our class:

<?php $arrHelper = new ArrHelper(); ?>

Let's find the sum of numbers of various arrays using our object:

<?php $sum1 = $arrHelper->getSum([1, 2, 3]); var_dump($sum1); $sum2 = $arrHelper->getSum([3, 4, 5]); var_dump($sum2); ?>

Make a Validator class, which will perform string validation for correctness.

Make a method in your class isEmail, checking if the string is a valid email.

Make a method in your class isDomain, checking if the string is a valid domain name.

Make a method in your class isNumber, checking if the string contains only numbers.

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