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);abstractclassParkingLot{publicfunction__construct(publicreadonlystring$name) { }abstractprotectedfunctionratePer30Min(): int;protectedfunctionfreeMinutes(): int {return0; }publicfunctionfee(int$minutes): int {$billable = max(0, $minutes - $this->freeMinutes());$blocks = intdiv($billable + 29, 30);return$blocks * $this->ratePer30Min(); }}finalclassMallLotextendsParkingLot{protectedfunctionratePer30Min(): int {return1000; }protectedfunctionfreeMinutes(): int {return60; }}finalclassStationLotextendsParkingLot{protectedfunctionratePer30Min(): int {return1500; }}try {$lot = newParkingLot('test');} catch (Error$e) {echo$e->getMessage(), "\n";}$lots = [newMallLot('Mall'), newStationLot('Station')];foreach ($lotsas$lot) {printf("%s: 95 min = %d won\n", $lot->name, $lot->fee(95));}
Press Run to try your edited code right away. The step-through and the output above follow the original code.
Choosing between abstract class, interface and trait
abstract class
interface
trait
Create directly with new
X
X
X
Methods with a body
O
X
O
Properties holding values
O
Constants only
O
One class can use several
X
O
O
Usable as a parameter type or with instanceof
O
O
X
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.
What PHP saysFatal error: Class TinyLot contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ParkingLot::ratePer30Min)
Fixed
abstractclassParkingLot{abstractprotectedfunctionratePer30Min(): int;publicfunctionhour(): int {return$this->ratePer30Min() * 2; }}finalclassTinyLotextendsParkingLot{protectedfunctionratePer30Min(): int {return700; }}echo (newTinyLot())->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
abstractclassParkingLot{abstractprotectedfunctionratePer30Min(): int {return0; }}
What PHP saysFatal error: Abstract function ParkingLot::ratePer30Min() cannot contain body
Fixed
abstractclassParkingLot{protectedfunctionratePer30Min(): int {return0; }}finalclassFreeLotextendsParkingLot{publicfunctionrate(): int {return$this->ratePer30Min(); }}echo (newFreeLot())->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
abstractclassParkingLot{abstractprotectedfunctionratePer30Min(): int;}finalclassMiniLotextendsParkingLot{privatefunctionratePer30Min(): int {return500; }}
What PHP saysFatal error: Access level to MiniLot::ratePer30Min() must be protected (as in class ParkingLot) or weaker
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.