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. The syntax for doing this is as follows:
<?php
// 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 implements Shape and Color interfaces and provides implementation for getArea() and getColor() methods
class Rectangle 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)
{
$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";
Watch a video course
Learn object oriented PHP
It is worth noting that a class can only extend one parent class but can implement multiple interfaces.