Thursday, 3 June 2021

Php: Interfaces

Interface is an abstract type that contain method signatures(It do not contain method definitions). Since interface describes the contract, it contains only public functions.

 

How to create an interface?

‘interface’ keyword is used to create an interface.

 

Syntax

interface InterfaceName{
    
    public function function_1(args);
    public function function_2(args);
    .....
    .....
    .....
}

 

Example

interface Circle{
    public function area_of_circle($radius);
    public function perimeter_of_circle($radius);
}

 

How to implement an interface?

Once an interface is defined, a class can implement this interface and provide definition of all the signatures declared interface.

 

Syntax

class ClassName implements InterfaceName{

    //Provide definition to all the method signatures of interface.

}

 

Example

class MyCircle implements Circle{
    public const PI = 3.14;

    public function area_of_circle($radius){
        return self::PI * $radius * $radius;
    }
    public function perimeter_of_circle($radius){
        return 2 * self::PI * $radius;
    }
}

 

Find the below working application.

 

interfaces.php

#!/usr/bin/php

<?php

interface Circle{
    public function area_of_circle($radius);
    public function perimeter_of_circle($radius);
}

class MyCircle implements Circle{
    public const PI = 3.14;

    public function area_of_circle($radius){
        return self::PI * $radius * $radius;
    }
    public function perimeter_of_circle($radius){
        return 2 * self::PI * $radius;
    }
}

$circle1 = new MyCircle();
$radius = 12;

$area = $circle1->area_of_circle($radius);
$perimeter = $circle1->perimeter_of_circle($radius);

echo "Radius of Circle : $radius\n";
echo "Area of Circle : $area\n";
echo "Perimeter of Circle : $perimeter\n";
?>

Output

$./interfaces.php 

Radius of Circle : 12
Area of Circle : 452.16
Perimeter of Circle : 75.36


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment