Interface in PHP – contract that must be kept!

In PHP, an interface is a powerful language construct that allows us to declare a set of methods that must be implemented by any class that adopts the interface. It defines a contract that a class must adhere to, specifying the methods that the class must implement without providing the actual implementation. Essentially, an interface defines a blueprint for a group of related functionalities.

Here’s a basic example of how an interface is defined in PHP:

// Define the Shape interface
interface Shape {
    public function calculateArea();
    public function calculatePerimeter();
}

In the above example:

  • Shape is the interface, and it declares two methods viz calculateArea and calculatePerimeter.
  • Circle and Square are classes that implement the Shape interface. They must provide an implementation for the calculateArea and calculatePerimeter method defined in the interface.

A class can implement multiple interfaces, and an interface can extend other interfaces. This allows you to organize your code in a modular and reusable way. I will explain this in another article.

// Implement the Shape interface in the Circle class
class Circle implements Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return pi() * $this->radius * $this->radius;
    }
    public function calculatePerimeter() {
        return pi() * $this->radius * $this->radius;
    }
}

// Implement the Shape interface in the Square class
class Square implements Shape {
    private $side;

    public function __construct($side) {
        $this->side = $side;
    }

    public function calculateArea() {
        return $this->side * $this->side;
    }
    public function calculatePerimeter() {
        return 4 * $this->side;
    }
}

// Create objects and calculate areas
$circle = new Circle(5);
$square = new Square(4);

echo "Circle Area: " . $circle->calculateArea() . "\n";
echo "Circle Perimeter: " . $circle->calculatePerimeter() . "\n";

echo "Square Area: " . $square->calculateArea() . "\n";
echo "Square Perimeter: " . $square->calculatePerimeter() . "\n";

Now, you can create objects of Circle and Square and calculate both the area and perimeter using the methods provided by the Shape interface. This demonstrates how interfaces can be extended to include additional methods while ensuring that implementing classes adhere to the new contract.

Get Free Email Updates!

Signup now and receive an email once I publish new content.

I agree to have my personal information transfered to MailChimp ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

Powered by Optin Forms

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *