Course Content
Autoloading
0/1
Exceptions Handling
0/1
PHP OOP
About Lesson

What are Interfaces:

Interfaces in PHP provide a way to define a contract for classes, specifying what methods a class must implement without dictating how they should be implemented. They define a set of methods that a class must implement, allowing for standardized behaviour across different classes.

Key Points about Interfaces:

Definition: An interface is defined using the interface keyword followed by the interface name and a code block containing method signatures (without method bodies).

PHP
<?php

interface Logger {

    public function log($message);

}

Implementing Interfaces: To implement an interface, a class uses the implements keyword followed by the interface name. The class must provide implementations for all the methods declared in the interface.

PHP
<?php

class FileLogger implements Logger {

    public function log($message) {

        // Log message to a file

    }

}

Multiple Interfaces: A class can implement multiple interfaces, separated by commas.

PHP
<?php

class DatabaseLogger implements Logger, ErrorHandler {

    // Implement methods from both Logger and ErrorHandler interfaces

}

Method Signatures: Interfaces only contain method signatures (the name, parameters, and return type of the method), but no method bodies. Classes implementing the interface provide the method implementations.

Interface Inheritance: Interfaces can extend other interfaces, allowing for the creation of a hierarchy of interfaces.

PHP
<?php

interface DatabaseLogger extends Logger {

    public function connect();

}

Abstract Methods: All methods declared in an interface are implicitly abstract, so they cannot contain method bodies.

Example:

PHP
<?php

interface Logger {

    public function log($message);

}

class FileLogger implements Logger {

    public function log($message) {

        // Log message to a file

    }

}

class DatabaseLogger implements Logger {

    public function log($message) {

        // Log message to a database

    }

}

?>

In this example, Logger is an interface defining a contract for classes that can log messages. Both FileLogger and DatabaseLogger implement the log() method defined in the Logger interface. Each class provides its own implementation of the log() method, specifying how messages should be logged to a file or a database, respectively.

Interfaces in PHP allow for standardized behaviour across different classes, promoting code consistency and flexibility. They enable polymorphism, allowing objects of different classes to be treated interchangeably based on their shared interface.