iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Inheritance

A subclass extends a parent — picking up its properties and methods, and optionally overriding them. PHP allows single inheritance only (use traits / interfaces for the rest).

The shape

PHP
class Animal {
    public function __construct(public string $name) {}
    public function speak(): string { return 'some sound'; }
}

class Dog extends Animal {
    public function speak(): string { return 'woof'; }
}

echo (new Dog('Rex'))->speak();    // woof
echo (new Dog('Rex'))->name;        // Rex

Calling the parent

PHP
class Cat extends Animal {
    public function __construct(string $name, public bool $indoor = true) {
        parent::__construct($name);
    }

    public function speak(): string {
        return parent::speak() . ' (purr)';
    }
}

final — stop further inheritance

PHP
final class Currency { ... }   // can't be extended

class Animal {
    final public function id(): string { ... }   // can't be overridden
}

Type checks

PHP
$d = new Dog('Rex');
var_dump($d instanceof Dog);        // true
var_dump($d instanceof Animal);     // true (subclass)
var_dump(is_subclass_of($d, Animal::class));   // true

Late static binding

static:: resolves to the runtime class, not the declaring class. Useful in factories that should return the subclass type:

PHP
class Model {
    public static function fresh(): static {
        return new static();
    }
}

class User extends Model {}
$u = User::fresh();
var_dump($u);   // object(User)
Tip: Composition often beats inheritance. "A Truck has an Engine" usually models reality better than "A Truck IS-A Engine".

Example

Example
<?php
class Animal {
    public function __construct(public string $name) {}
    public function speak(): string { return 'some sound'; }
}
class Dog extends Animal {
    public function speak(): string { return 'woof'; }
}
echo (new Dog('Rex'))->speak();
Try it Yourself »

Exercise

Subclass another class with…

class Dog Animal {}

Test yourself

Q1. PHP allows… inheritance.
Q2. Late static binding keyword is…
Q3. final prevents…

Discussion

Loading…