Skip to content

Can a class extend both a class and implement an Interface โ€‹

Yes, a class in PHP can extend another class and implement one or more interfaces at the same time. Note that the extends keyword must come before the implements keyword in the class declaration. The syntax for doing this is as follows:

Example of a class extending a class and implementing an Interface at the same time in PHP

php
<โ€Œ?php

// Parent class
class GeometricShape
{
    protected $name;

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

    public function getName()
    {
        return $this->name;
    }
}

// Shape interface defines a contract for classes to implement the method getArea()
interface Shape
{
    public function getArea();
}

// Color interface defines a contract for classes to implement the method getColor()
interface Color
{
    public function getColor();
}

// Rectangle class extends GeometricShape and implements Shape and Color interfaces
class Rectangle extends GeometricShape implements Shape, Color
{
    // Declare class properties
    private $width;
    private $height;
    private $color;

    // Constructor to set the values of width, height and color properties
    public function __construct($width, $height, $color)
    {
        parent::__construct("Rectangle");
        $this->width = $width;
        $this->height = $height;
        $this->color = $color;
    }

    // Implementation of getArea() method from Shape interface
    public function getArea()
    {
        return $this->width * $this->height;
    }

    // Implementation of getColor() method from Color interface
    public function getColor()
    {
        return $this->color;
    }
}

// Create an instance of Rectangle class
$rect = new Rectangle(10, 20, "red");

// Use the methods of Rectangle class
echo "The area of the rectangle is: " . $rect->getArea() . "\n";
echo "The color of the rectangle is: " . $rect->getColor() . "\n";
echo "The shape name is: " . $rect->getName() . "\n";

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

It is worth noting that a class can only extend one parent class but can implement multiple interfaces. When combining both, the extends clause must always precede the implements clause.

Dual-run preview โ€” compare with live Symfony routes.