HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP OOP - Interfaces

In PHP Object-Oriented Programming (OOP), interfaces define a contract for classes to implement.
An interface specifies a set of methods that a class must implement.
Unlike abstract classes, interfaces cannot contain any concrete methods or properties; they only declare the method signatures (names, parameters, and return types).

Example

// Interface definition
interface MyInterface {
    // Method declaration (no implementation)
    public function method1();
    
    // Another method declaration
    public function method2($param);
}

// Class implementing the interface
class MyClass implements MyInterface {
    // Implementation of method1() declared in MyInterface
    public function method1() {
        echo "Implementation of method1.\n";
    }
    
    // Implementation of method2() declared in MyInterface
    public function method2($param) {
        echo "Implementation of method2 with parameter: $param.\n";
    }
}

// Creating an object of the class implementing the interface
$obj = new MyClass();

// Calling methods declared in the interface
$obj->method1();
$obj->method2("Hello");

You can click on above box to edit the code and run again.

Output

In this example:

  • MyInterface is an interface defined using the interface keyword.
  • It contains method declarations without implementations.
  • MyClass is a class that implements MyInterface.
  • MyClass must provide concrete implementations for all methods declared in MyInterface.
  • An object of MyClass can be created and methods declared in the interface can be called on it.
  • Interfaces are useful for defining a contract that classes must adhere to, without prescribing any specific implementation details.
  • They help in achieving polymorphism and loose coupling in your code, allowing different classes to be used interchangeably if they implement the same interface.

PHP - Interfaces vs. Abstract Classes

Interface are similar to abstract classes. The difference between interfaces and abstract classes are:

Interfaces cannot have properties, while abstract classes can
All interface methods must be public, while abstract class methods is public or protected
All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary
Classes can implement an interface while inheriting from another class at the same time