Tools
Log in
English

Learn to codePHP

PHP polymorphism

Based on PHP 8.3

One pay() call handles card, bank transfer and points through a PHP interface.

In one line

Polymorphism means one method call behaves differently depending on the class of the object. In PHP an interface spells out the promise that a method exists, and a parameter typed with that interface accepts any class that keeps it.

Why you need it

Checkout code full of if ($type === 'card') ... elseif ($type === 'bank') ... must be hunted down and edited everywhere whenever a new payment method appears. Miss one spot and payments go wrong.

Give each method its own class with its own pay(), and checkout shrinks to $method->pay($amount). A new method is one new class.

Everyday picture

Think of a card terminal at a shop. The clerk presses the same pay button whether the customer inserts a card or taps a phone. Each method is processed differently, but anything that fits the terminal (the interface) is accepted.

Example code

main.php · 53 lines
<?phpdeclare(strict_types=1); interface PaymentMethod{    public function pay(int $amount): string;} final class CardPayment implements PaymentMethod{    public function __construct(private string $last4)    {    }     public function pay(int $amount): string    {        $fee = intdiv($amount * 2, 100);        return "card *{$this->last4}: $amount + fee $fee";    }} final class BankTransfer implements PaymentMethod{    public function pay(int $amount): string    {        return "bank transfer: $amount, no fee";    }} final class PointPayment implements PaymentMethod{    public function __construct(private int $points)    {    }     public function pay(int $amount): string    {        $used = min($this->points, $amount);        $this->points -= $used;        return "points: $used used, " . ($amount - $used) . ' left';    }} function checkout(PaymentMethod $method, int $amount): void{    echo get_class($method), ' -> ', $method->pay($amount), "\n";} $methods = [new CardPayment('4821'), new BankTransfer(), new PointPayment(7000)];foreach ($methods as $m) {    checkout($m, 12000);}var_dump($methods[1] instanceof PaymentMethod);

When to use it

  • There are several ways to do the same job and more are coming (payments, notifications, storage)
  • Branches on instanceof or a $type string repeat across files
  • You want to swap in a fake object during tests

PHP does not treat a matching method name as keeping a contract (unlike duck typing in Python). To pass an object into a typed parameter, the class must say implements.

Common mistakes

Matching the method name but skipping implements

Having a pay() method is not enough. Without implements PaymentMethod, PHP does not treat the class as keeping the contract, and a typed parameter checks that label.

Wrong

interface PaymentMethod{    public function pay(int $amount): string;} final class Cash{    public function pay(int $amount): string    {        return "cash: $amount";    }} function checkout(PaymentMethod $m): void{    echo $m->pay(5000), "\n";} checkout(new Cash());

When you run itFatal error: Uncaught TypeError: checkout(): Argument #1 ($m) must be of type PaymentMethod, Cash given

Fixed

interface PaymentMethod{    public function pay(int $amount): string;} final class Cash implements PaymentMethod{    public function pay(int $amount): string    {        return "cash: $amount";    }} function checkout(PaymentMethod $m): void{    echo $m->pay(5000), "\n";} checkout(new Cash());

When you run itcash: 5000

Branching on instanceof for every type

A new phone payment was added, nobody updated feeFor(), and the fee silently became 0. Move the calculation into each class; a new type then just writes its own fee().

Wrong

final class CardPayment{} final class PhonePayment{} function feeFor(object $m, int $amount): int{    if ($m instanceof CardPayment) {        return intdiv($amount * 2, 100);    }    return 0;} echo feeFor(new PhonePayment(), 12000), "\n";

When you run it0

Fixed

interface PaymentMethod{    public function fee(int $amount): int;} final class CardPayment implements PaymentMethod{    public function fee(int $amount): int    {        return intdiv($amount * 2, 100);    }} final class PhonePayment implements PaymentMethod{    public function fee(int $amount): int    {        return intdiv($amount * 3, 100);    }} function feeFor(PaymentMethod $m, int $amount): int{    return $m->fee($amount);} echo feeFor(new PhonePayment(), 12000), "\n";

When you run it360

Implementing an interface method as non-public

Interface methods are public promises, so the implementation must be public too. Put helpers you want hidden in separate private methods that are not part of the interface.

Wrong

interface PaymentMethod{    public function pay(int $amount): string;} final class CardPayment implements PaymentMethod{    protected function pay(int $amount): string    {        return "card: $amount";    }}

What PHP saysFatal error: Access level to CardPayment::pay() must be public (as in class PaymentMethod)

Fixed

interface PaymentMethod{    public function pay(int $amount): string;} final class CardPayment implements PaymentMethod{    public function pay(int $amount): string    {        return "card: $amount";    }} echo (new CardPayment())->pay(800), "\n";

When you run itcard: 800

Check yourself

Question 1

What prints when 500 points pay for 800?

checkout(new PointPayment(500), 800);

Show the answer

Answer: 1. PointPayment -> points: 500 used, 300 left min(500, 800) is 500, so 500 is used and 300 is left. checkout() takes any payment method with the same line.

Question 2

In PHP 8.3, what can an interface contain?

Show the answer

Answer: 2. Constants and method signatures (name, parameters, return type) An interface only promises that certain methods exist. Bodies and stored values belong to the implementing class. PHP 8.4 also allows properties with hooks in interfaces (new in 8.4).

Questions people ask

Does a matching method name make a class fit an interface?

No. The class must say implements InterfaceName before it fits a parameter of that type; otherwise PHP throws a TypeError.

What is wrong with branching on instanceof?

Every new type means hunting down and editing each branch, and one is easily missed. Move the calculation into each class and a new type is just one more class.

Can a class implement several interfaces?

Yes, list them with commas: implements A, B. A class still extends only one parent.