Tools
Log in
English

Learn to codePHP

PHP abstraction

Based on PHP 8.3

An abstract parking lot fixes the fee steps while children set the rates.

In one line

Abstraction fixes what has to happen first and leaves how for later. A PHP abstract class leaves some methods empty; you cannot new it, and a child has to fill in the blanks before it can be used.

Why you need it

If every parking lot has its own fee function, the steps (subtract free time, round up to 30 minutes, multiply by the rate) drift apart. One file rounds down, another rounds up, and the bills disagree.

Keep the steps in the parent fee() once and let children set only the rate and the free minutes. The calculation can no longer drift, and a new lot is two numbers.

Everyday picture

Think of a receipt form sent out by head office: time in, time out, discount, total, always in that order. Each branch only writes its own rate and cannot reorder the lines. The head office form is the abstract class; the branch rate is the method the child fills in.

Example code

main.php · 54 lines
<?phpdeclare(strict_types=1); abstract class ParkingLot{    public function __construct(public readonly string $name)    {    }     abstract protected function ratePer30Min(): int;     protected function freeMinutes(): int    {        return 0;    }     public function fee(int $minutes): int    {        $billable = max(0, $minutes - $this->freeMinutes());        $blocks = intdiv($billable + 29, 30);        return $blocks * $this->ratePer30Min();    }} final class MallLot extends ParkingLot{    protected function ratePer30Min(): int    {        return 1000;    }     protected function freeMinutes(): int    {        return 60;    }} final class StationLot extends ParkingLot{    protected function ratePer30Min(): int    {        return 1500;    }} try {    $lot = new ParkingLot('test');} catch (Error $e) {    echo $e->getMessage(), "\n";}$lots = [new MallLot('Mall'), new StationLot('Station')];foreach ($lots as $lot) {    printf("%s: 95 min = %d won\n", $lot->name, $lot->fee(95));}

Choosing between abstract class, interface and trait

abstract classinterfacetrait
Create directly with newXXX
Methods with a bodyOXO
Properties holding valuesOConstants onlyO
One class can use severalXOO
Usable as a parameter type or with instanceofOOX

In short: if the parent must own the shared steps and code, use an abstract class; for a pure contract, an interface; to paste the same code into several classes, a trait. They also combine well (an interface for the contract plus an abstract class for a default implementation).

When to use it

  • Several classes follow the same steps and differ in a few (the template method pattern)
  • The parent alone must not be created because blanks remain
  • Children should inherit shared properties (such as a name) and shared code as is

In the class diagram, italic names are abstract methods. If a child leaves a blank, PHP stops while loading that class, so an empty method can never be called at run time.

Common mistakes

A child that leaves an abstract method empty

If the child does not fill in a method the parent left abstract, PHP stops as soon as it loads the class. The missing method is named in parentheses at the end of the message.

Wrong

abstract class ParkingLot{    abstract protected function ratePer30Min(): int;} final class TinyLot extends ParkingLot{}

What PHP saysFatal error: Class TinyLot contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ParkingLot::ratePer30Min)

Fixed

abstract class ParkingLot{    abstract protected function ratePer30Min(): int;     public function hour(): int    {        return $this->ratePer30Min() * 2;    }} final class TinyLot extends ParkingLot{    protected function ratePer30Min(): int    {        return 700;    }} echo (new TinyLot())->hour(), "\n";

When you run it1400

Giving an abstract method a body

abstract means the child writes the body, so braces are not allowed. If you want a default, drop abstract and write a normal method that children may override.

Wrong

abstract class ParkingLot{    abstract protected function ratePer30Min(): int    {        return 0;    }}

What PHP saysFatal error: Abstract function ParkingLot::ratePer30Min() cannot contain body

Fixed

abstract class ParkingLot{    protected function ratePer30Min(): int    {        return 0;    }} final class FreeLot extends ParkingLot{    public function rate(): int    {        return $this->ratePer30Min();    }} echo (new FreeLot())->rate(), "\n";

When you run it0

Narrowing visibility in the child

If the child turns a protected method into private, the parent code that calls it would break. When overriding, keep the same visibility or widen it (protected to public).

Wrong

abstract class ParkingLot{    abstract protected function ratePer30Min(): int;} final class MiniLot extends ParkingLot{    private function ratePer30Min(): int    {        return 500;    }}

What PHP saysFatal error: Access level to MiniLot::ratePer30Min() must be protected (as in class ParkingLot) or weaker

Fixed

abstract class ParkingLot{    abstract protected function ratePer30Min(): int;     public function show(): string    {        return static::class . ' ' . $this->ratePer30Min();    }} final class MiniLot extends ParkingLot{    protected function ratePer30Min(): int    {        return 500;    }} echo (new MiniLot())->show(), "\n";

When you run itMiniLot 500

Check yourself

Question 1

What does the mall lot charge for 60 minutes?

echo (new MallLot('A'))->fee(60), "\n";

Show the answer

Answer: 1. 0 The first 60 minutes are free at the mall, so nothing is billable. 0 blocks x 1000 = 0.

Question 2

When is an abstract class a better pick than an interface?

Show the answer

Answer: 3. When the parent owns the steps and shared code and children fill in only parts An abstract class can hold finished methods (fee()) next to blanks (ratePer30Min()). It fits when the parent fixes the steps and children supply the numbers. For a contract alone, an interface is lighter.

Questions people ask

Can I create an object from an abstract class?

No. new fails with Cannot instantiate abstract class. Create a child class that fills in the blanks.

Abstract class or interface?

If the parent must own shared code and the order of steps, an abstract class; for a contract only, an interface. They are often combined.

Can a trait replace an abstract class?

A trait is pasted code and cannot be used as a type. Put the contract in an interface and the shared code in a trait.