К основному содержимому
УРОК 5 ИЗ 15

ООП в PHP: классы, интерфейсы, трейты

2 Теория

Класс

<?php
declare(strict_types=1);

class Product
{
    public function __construct(
        private string $name,
        private float $price,
        private int $stock = 0,
    ) {}                               // свойства через конструктор (PHP 8)

    public function getName(): string { return $this->name; }
    public function priceWithVat(float $rate = 0.2): float { return round($this->price * (1 + $rate), 2); }
    public function sell(int $qty): void
    {
        if ($qty > $this->stock) { throw new RuntimeException("Недостаточно товара"); }
        $this->stock -= $qty;
    }
}

$p = new Product("Книга", 300, 5);
echo $p->priceWithVat();

Наследование и интерфейсы

interface Payable { public function pay(float $sum): bool; }

abstract class Method implements Payable {
    abstract protected function fee(): float;
    public function pay(float $sum): bool { return $sum + $this->fee() > 0; }
}
final class Card extends Method { protected function fee(): float { return 1.5; } }
  • public / protected / private — уровни доступа;
  • interface задаёт контракт, abstract class — частичную реализацию;
  • final запрещает наследование; static и const принадлежат классу, а не объекту;
  • readonly-свойства (PHP 8.1) неизменяемы после создания.

Трейты и enum

trait Timestamps { public ?string $createdAt = null; public function touch(): void { $this->createdAt = date('c'); } }
enum Status: string { case New = 'new'; case Paid = 'paid'; }