PHP
abstract methods
Learn to declare bodyless methods with abstract method and implement them in subclasses.
abstract method: bodyless declaration
An abstract class can declare methods that subclasses must fill in their own way. This is called an abstract method. It has no body; only the signature is written and it ends with a semicolon.
The declaration is: abstract public function area(): float;. Note: no { }, no body; just a ; at the end. The subclass must implement this method with its own body (concrete implementation).
This lets the parent say 'every shape computes an area, but you decide how'. The parent sets the contract; the child provides the implementation.
Abstract method and concrete implementation
To declare an abstract method, put the abstract keyword in front: abstract public function area(): float;. Instead of a body, there is only the signature and a ;.
The subclass must implement this method with the same signature. Example:
abstract class Shape {
abstract public function area(): float;
}
class Circle extends Shape {
public function area(): float {
return 3.14;
}
}
$c = new Circle();
echo $c->area();
If Circle does not implement the abstract method, PHP errors. When it does, $c->area() returns 3.14.
Exercise Abstract method: implement in a subclass
Define a Shape abstract class. Declare abstract public function area(): float; (no body, semicolon). Add a public function describe(): string method that does return "Area: " . $this->area();. Then derive Circle from Shape and implement area() with return 3.14;. Use $c = new Circle() and echo $c->describe() . "\n".
Show example solution
float;. Inside describe() call $this->area(). In Circle implement area() with return 3.14;.
Example solution:
<?php
// Define the Shape abstract class, declare the area() method
abstract class Shape {
abstract public function area(): float;
public function describe(): string {
return "Area: " . $this->area();
}
}
class Circle extends Shape {
public function area(): float {
return 3.14;
}
}
$c = new Circle();
echo $c->describe() . "\n";
Test yourself
-
Which is a valid abstract method declaration?
- abstract public function area(): float { return 0; }
- public abstract function area(): float = 0;
- abstract public function area(): float;
- function area(): float abstract;
Show answer
abstract public function area(): float; — Correct. abstract public function area(): float; is the bodyless declaration ending with a semicolon.
-
Abstract method declaration
abstract class Shape {
____
}
Show answer
abstract class Shape {
abstract public function area(): float;
}
-
Match the abstract method concepts
- abstract method
- Bodyless signature
- method signature
- Parameters and return type
- concrete implementation
- Body in the subclass
- semicolon
- Ends the signature
Next lesson: Abstract class inheritance