Inheritance & Interfaces
⏱ 20 min read read
Inheritance in PHP:
class Dog extends Animal {
// Dog inherits everything from Animal
}
parent:: --- Calling the Parent:
public function \_\_construct(string $name, int $age, string
$breed) {
parent::\_\_construct($name, $age); // call Animal's constructor
$this->breed = $breed;
}
PHP uses parent:: (not super() like Java/Python).
Method overriding works the same --- define same method name in
child.
PHP uses extends for inheritance (same keyword as Java).
PHP supports only SINGLE inheritance (one parent class).
Use interfaces for multiple type contracts.
Interfaces:
An interface defines a contract --- methods a class must implement. No
method bodies.
interface Shape {
public function area(): float;
public function perimeter(): float;
}
class Circle implements Shape {
public function \_\_construct(private float $radius) {}
public function area(): float { return M_PI * $this->radius **
2; }
public function perimeter(): float { return 2 * M_PI *
$this->radius; }
}
Abstract Classes:
Cannot be instantiated directly. May have abstract methods (no body)
that subclasses must implement.
abstract class Animal {
abstract public function makeSound(): string; // must implement
public function describe(): void { // can use directly
echo $this->makeSound();
}
}
final Keyword:
final class --- cannot be extended. final method --- cannot be
overridden.
class Dog extends Animal {
// Dog inherits everything from Animal
}
parent:: --- Calling the Parent:
public function \_\_construct(string $name, int $age, string
$breed) {
parent::\_\_construct($name, $age); // call Animal's constructor
$this->breed = $breed;
}
PHP uses parent:: (not super() like Java/Python).
Method overriding works the same --- define same method name in
child.
PHP uses extends for inheritance (same keyword as Java).
PHP supports only SINGLE inheritance (one parent class).
Use interfaces for multiple type contracts.
Interfaces:
An interface defines a contract --- methods a class must implement. No
method bodies.
interface Shape {
public function area(): float;
public function perimeter(): float;
}
class Circle implements Shape {
public function \_\_construct(private float $radius) {}
public function area(): float { return M_PI * $this->radius **
2; }
public function perimeter(): float { return 2 * M_PI *
$this->radius; }
}
Abstract Classes:
Cannot be instantiated directly. May have abstract methods (no body)
that subclasses must implement.
abstract class Animal {
abstract public function makeSound(): string; // must implement
public function describe(): void { // can use directly
echo $this->makeSound();
}
}
final Keyword:
final class --- cannot be extended. final method --- cannot be
overridden.
Log in to track your progress and earn badges as you complete lessons.
Log In to Track Progress