اینترفیس (Interface) قراردادی برای رفتار قابل ارائه یک نوع است. کلاسها یا انواع مختلف میتوانند یک قرارداد مشترک را پیادهسازی کنند تا کد مصرفکننده به پیادهسازی مشخص وابسته نباشد. اینترفیس تنها به PHP محدود نیست.
مثال در PHP
interface PaymentGateway { public function charge(int $amount): bool; }
final class BankGateway implements PaymentGateway {
public function charge(int $amount): bool { return $amount > 0; }
}
مثال در Python با Protocol
from typing import Protocol
class PaymentGateway(Protocol):
def charge(self, amount: int) -> bool: ...
مثال در Go
type PaymentGateway interface { Charge(amount int64) bool }
// Implementations satisfy interfaces implicitly.
مثال در C#
public interface IPaymentGateway { bool Charge(decimal amount); }
public class BankGateway : IPaymentGateway {
public bool Charge(decimal amount) => amount > 0;
}
در پایتون میتوان از ABC یا Protocol استفاده کرد، در Go پیادهسازی اینترفیس بهصورت ضمنی است، و در PHP و C# بهصورت صریح تعریف میشود.
برای تفاوت آن با کلاس Abstract، ابسترکشن را بررسی کنید.