Open In App

What is the difference between implements and extends in PHP ?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

PHP facilitates two keywords, i.e. the implements and extends keywords, which can be used in the context of class inheritance and interface implementation. While both keywords are related to the concept of Object-Oriented Programming, they serve different purposes.

Extends Keyword

The extends keyword is used to create a subclass that inherits from another class. Inheritance is a fundamental concept in object-oriented programming, allowing a class to inherit the properties and methods of another class.

Syntax

class First {
public function parent() {
// Code...
}
}
class Second extends First {
// Code...
}

Example: Implementation of extend keyword in PHP.

PHP




<?php
 
class ParentClass
{
    public function parentMethod()
    {
        echo "This is a method from the parent class.\n";
    }
}
 
class ChildClass extends ParentClass
{
    public function childMethod()
    {
        echo "This is a method from the child class.\n";
    }
}
 
$childObj = new ChildClass();
$childObj->parentMethod();
$childObj->childMethod();
 
?>


Output

This is a method from the parent class.
This is a method from the child class.



Implements Keyword

The implements keyword is used to declare that a class implements one or more interfaces. An interface defines a contract that implementing classes must adhere to, specifying a set of methods that the class must implement.

Syntax

interface MyInterface
{
// Method...
}

class MyClass implements MyInterface
{
// Method...
}

Example: Implementation of implements keyword in PHP.

PHP




<?php
 
interface MyInterface
{
    public function interfaceMethod();
}
 
class MyClass implements MyInterface
{
    public function interfaceMethod()
    {
        echo "This is the implementation of the interface method.\n";
    }
}
 
$obj = new MyClass();
$obj->interfaceMethod();
 
?>


Output

This is the implementation of the interface method.



Differences Between Implements and Extends

Now, let’s summarize the key differences between implements and extends:

Parameters Implements Extends
Purpose Implements interfaces Extends a class
Syntax class MyClass implements MyInterface class ChildClass extends ParentClass
Inheritance No inheritance from the interface Inheriting properties and methods from the parent class
Multiple Usage Can implement multiple interfaces Can only extend one class
Abstract Classes Can implement abstract classes Can only extend concrete (non-abstract) classes
Code Reusability Promotes code reusability through interface implementation Promotes code reusability through class inheritance


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads