PHP Object Interfaces Keyword

PHP Object Interfaces Keyword

Using object interfaces with PHP OOP is useful when you want to make sure a class must contain specific public functions. In other words, if you want to use an interface for a class, the class must use the method from the interface, otherwise an error will occur.

Another key point to remember with interfaces is that the class and interface code blocks must use public methods with the same amount of parameters. Although the parameters must be the same, the actual names in the interface code block is not that important, asides from good type hinting.

To use interfaces, you make a code block with the interface keyword. This is much like declaring a class, but with a different name. To use the interface conditions in a class, you add the implements keyword followed by the name. The example below should make this clear.

Example #1

<?php

interface example
{
    public function set_name($var1,$var2);
    public function get_name();
}

Class Test implements example
{
    public $var1;
    public $var2;
    public $var3;
    

    public function set_name($var1, $var2)
    {
        $this->var3 = $var1 . " " . $var2;

    }

    public function get_name()
    {

        return $this->var3;

    }


}

$my_test = new Test();
$my_test->set_name('Peter', 'Paul');
echo $my_test->get_name();


Browser Output

Peter Paul


Example #2

Here is an example of code that is slightly modified from above. The only difference is the reduction of one parameter from the interface code block. Thus, 'public function set_name($var1,$var2)' was changed to 'public function set_name($var1)'. The code below would trigger an error because the parameters in the class and interface are different.

interface example
{
    public function set_name($var1);
    public function get_name();
}

Class Test implements example
{
    public $var1;
    public $var2;
    public $var3;
    

    public function set_name($var1, $var2)
    {
        $this->var3 = $var1 . " " . $var2;

    }

    public function get_name()
    {

        return $this->var3;

    }


}

$my_test = new Test();
$my_test->set_name('Peter', 'Paul');
echo $my_test->get_name();