Web Analytics

PHP Interfaces

Intermediate~30 min read

Interfaces define contracts that classes must follow. Unlike abstract classes, a class can implement multiple interfaces - perfect for defining capabilities!

Output
Click Run to execute your code
PHP Interfaces - Contract and Implementation

Defining an Interface

<?php
interface PaymentInterface {
    public function processPayment($amount);
    public function refund($transactionId);
}
?>

Implementing an Interface

<?php
class CreditCardPayment implements PaymentInterface {
    public function processPayment($amount) {
        echo "Processing $$amount";
    }
    
    public function refund($transactionId) {
        echo "Refunding $transactionId";
    }
}
?>

Multiple Interfaces

<?php
class Payment implements PaymentInterface, Loggable {
    // Must implement all methods from both interfaces
}
?>
PHP Access Modifiers - public, protected, private

Three Access Levels

  • interface: Contract definition
  • implements: Follow the contract
  • Multiple: Can implement many interfaces
  • All public: Interface methods are always public

What's Next?

Next, learn about Traits - horizontal code reuse without inheritance!