PHP Inheritance

PHP Inheritance

Inheritance in OOP is when a class derives from another class. This allows you to share properties and methods across multiple classes, reducing repetitive code.

The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own customized properties and methods.


The extends Keyword

An inherited class is defined by using the extends keyword.

Inheritance Example

<?php
class Animal {
  public $name;
  

public function sleep() { echo "Zzzzz...\n"; } }

// Dog inherits from Animal class Dog extends Animal { public function bark() { echo "Woof! Woof!\n"; } }

$myDog = new Dog(); $myDog->name = "Buddy"; // Inherited property $myDog->sleep(); // Inherited method $myDog->bark(); // Unique to Dog ?>


Overriding Inherited Methods

Inherited methods can be overridden (changed) by redefining the method inside the child class with the exact same name.

If a child class has a method named sleep(), calling it will execute the child's version instead of the parent's version. This allows child classes to customize generic behaviors.

The final Keyword

Sometimes, you want to prevent a class from being inherited or prevent a method from being overridden. You can do this by prefixing the class or method with the final keyword.

final class Car { ... } cannot be extended.

final public function drive() { ... } cannot be overridden.