PHP Interfaces
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
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
}
?>
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!
Enjoying these tutorials?