⊗ppOpIfPm 69 of 107 menu

Parameters in Interface Methods in OOP in PHP

When describing methods in interfaces, it is necessary to specify not only the names of the methods themselves, but also the parameters they accept.

Let's look at an example. Let's say we have an interface iMath that describes a class for mathematical operations of addition, subtraction, multiplication, and division. Let this interface look like this:

<?php interface iMath { public function sum(); public function subtract(); public function multiply(); public function divide(); } ?>

Currently, the methods of our interface do not accept any parameters. And in fact, the methods of the class that will implement this interface also should not accept parameters, otherwise there will be an error.

Let's specify the method parameters in our interface:

<?php interface iMath { public function sum($a, $b); public function subtract($a, $b); public function multiply($a, $b); public function divide($a, $b); } ?>

Now let's write the implementation of our interface:

<?php class Math implements iMath { public function sum($a, $b) { return $a + $b; } public function subtract($a, $b) { return $a - $b; } public function multiply($a, $b) { return $a * $b; } public function divide($a, $b) { return $a / $b; } } ?>

If you try to set a different number of parameters in our class - we simply will not succeed: PHP will throw an error. Thus we cannot accidentally forget a parameter, nor accidentally add an extra one.

Let's say we are given an interface iUser:

<?php interface iUser { public function setName($name); public function getName(); public function setAge($age); public function getAge(); } ?>

Create a User class that will implement this interface.

Afrikaans
AzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEnglishEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
Ons gebruik koekies vir die werking van die webwerf, ontleding en personalisering. Die verwerking van data geskied volgens die Privaatheidsbeleid.
aanvaar alles instel verwerp