Interfaces in PHP OOP

How do Interfaces work in PHP?

Interfaces let you tell a class what methods it should have.

Interfaces make it easy for different classes to be used in the same way. \”Polymorphism\” means that more than one class can use the same interface.

The interface keyword is used to declare an interface:

Syntax

<?php
interface Interface_Name {
public function testMethod1();
public function testMethod2($one, $two);
public function testMethod3() : string;
}
?>

PHP: Abstract Classes vs. Interfaces

Interfaces are like abstract classes in a way. Interfaces and abstract classes are different in the following ways:

  • Abstract classes can have properties, but interfaces can\’t. All interface methods have to be public, but abstract class methods can be either public or protected.
  • All of the methods in an interface are abstract, so they can\’t be used in code, and you don\’t need to use the abstract keyword.
  • Classes can implement an interface at the same time that they inherit from another class.

Using Interfaces in PHP

A class must use the implements keyword if it wants to use an interface.

When a class implements an interface, it must also implement all of the methods in the interface.

Example

<!DOCTYPE html>
<html>
<body>

<?php
interface Color {
public function showcolorname();
}

class Red implements Color {
public function showcolorname() {
echo \”Red Color\”;
}
}

$color = new Red();
$color->showcolorname();
?>

</body>
</html>

Output

Red Color

Related Posts
How to Fix WordPress\’s White Screen of Death issue

Don\'t be alarmed if you get a WordPress error message or a white screen. Someone has most certainly seen the Read more

How to Find Wi-Fi network password in Windows 11, Windows 10, Windows 8, Windows 7

If you have another Windows PC already connected to your Wi-Fi network, you can use it to find the password Read more

coderazaa IFSC Code

What exactly is an IFSC code? The Indian Financial System Code (IFSC) is an 11-digit alphanumeric code that uniquely identifies Read more

RTE income limit 2024-25

Welcome to our site phponline.in. We\'ve provided you a lot of material today, and we\'d already given you a heads-up Read more

What is a Facebook Pixel Code? How do you get one? How do I add a Pixel Code it to website?

This guide will walk you through the steps of generating or locating your Facebook pixel code and integrating it into Read more

CSS Introduction

CSS: The Art of Styling Web Pages Cascading Style Sheets (CSS) is a powerful language that allows you to control Read more

Copy data from one MS Access database to another

Copy Data from One MS Access Database to Another In Microsoft Access, it's often necessary to transfer data between databases. Read more

TOC Menu Fails to Collapse When Hosting _build/html on Webserver

Introduction When building documentation using Sphinx and deploying the _build/html on a webserver, users may encounter an issue where the Read more

Scroll to Top