← कोर्स पर वापस जाएँ: PHP from scratch

Interfaces, traits, enums and abstract classes

वीडियो जल्द आ रहा है

Simple inheritance is not enough to design well. Sometimes you want to say "any object that knows how to do X" no matter which class it comes from; at other times, reuse a piece of code in unrelated classes; and at others, represent a closed set of possible values, such as the statuses of an order. PHP offers a tool for each need: interfaces, abstract classes, traits and enums. In this lesson you will see when to use each one and how to avoid the typical beginner mistakes.

Interfaces: a contract

An interface declares which methods a class must have, without writing their code. The classes that implement it with implements promise to fulfil the contract. Its great advantage: the rest of the program depends on the interface, not on a concrete class, so you can swap one implementation for another without touching the code that uses it. For example, a function that accepts a Logger works the same with a logger that writes to a file or with a test one. A class can implement several interfaces.

php
<?php

declare(strict_types=1);

interface Logger
{
    public function log(string $message): void;
}

final class EchoLogger implements Logger
{
    public function log(string $message): void
    {
        echo '[LOG] ', $message, "\n";
    }
}

final class MemoryLogger implements Logger
{
    /** @var list<string> */
    public array $lines = [];

    public function log(string $message): void
    {
        $this->lines[] = $message;
    }
}

function register(string $user, Logger $logger): void
{
    $logger->log("User registered: $user");
}

register('ana', new EchoLogger());   // [LOG] User registered: ana
$memory = new MemoryLogger();
register('luis', $memory);
echo count($memory->lines), "\n";    // 1

Abstract classes and traits

An abstract class cannot be instantiated: it serves as a common base and can mix already written methods with abstract ones that each child must complete. A trait is a package of methods and properties that is "pasted" into a class with use, useful for sharing behavior between unrelated classes, such as a creation-date method. It is code reuse, not a type: you cannot ask for a trait as a parameter. Use them sparingly, because too many traits hide where each method comes from.

php
<?php

declare(strict_types=1);

trait HasCreatedAt
{
    private ?DateTimeImmutable $createdAt = null;

    public function createdAt(): DateTimeImmutable
    {
        return $this->createdAt ??= new DateTimeImmutable();
    }
}

abstract class Shape
{
    abstract public function area(): float;

    public function describe(): string
    {
        return static::class . ' with area ' . number_format($this->area(), 2);
    }
}

final class Circle extends Shape
{
    use HasCreatedAt;

    public function __construct(private float $radius)
    {
    }

    public function area(): float
    {
        return M_PI * $this->radius ** 2;
    }
}

final class Rectangle extends Shape
{
    public function __construct(private float $w, private float $h)
    {
    }

    public function area(): float
    {
        return $this->w * $this->h;
    }
}

foreach ([new Circle(1.0), new Rectangle(2.0, 3.0)] as $shape) {
    echo $shape->describe(), "\n";
}
// Circle with area 3.14
// Rectangle with area 6.00
// new Shape();  // Error: cannot instantiate abstract class

Enums: closed sets of values

An enum defines a fixed set of valid cases. It is much safer than using loose strings such as 'pending' or 'shipped', because a typing mistake is detected immediately. A backed enum associates each case with a string or int value, useful for storing it in the database: from() converts a value into a case (throws an error if it does not exist) and tryFrom() returns null. Enums can have methods and implement interfaces, and they combine very well with match.

php
<?php

declare(strict_types=1);

enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Shipped = 'shipped';

    public function label(): string
    {
        return match ($this) {
            self::Pending => 'Waiting for payment',
            self::Paid => 'Payment received',
            self::Shipped => 'On its way',
        };
    }
}

$status = OrderStatus::from('paid');
echo $status->label(), "\n";                 // Payment received
echo $status->value, "\n";                   // paid
var_dump(OrderStatus::tryFrom('lost'));      // NULL

function canCancel(OrderStatus $s): bool
{
    return $s === OrderStatus::Pending;
}
var_dump(canCancel(OrderStatus::Shipped));   // bool(false)

जो सीखा उसे परखें

प्रश्न 1 / 1

What does OrderStatus::tryFrom('lost') return if the value does not exist?

✎ मेरे नोट्स

केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर

← पिछलाअगला →