⊗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. Suppose we have an interface iMath that describes a class for the 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 parameters of the methods 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); } ?>

Let's now 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 we 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.

Suppose we are given the following interface iUser:

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

Make a class User that will implement this interface.

byenru