Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 16 / 68

Inheritance (Extending a Class)

In this lesson you will learn class inheritance in PHP with extends, so you can design classes that share functionality efficiently. This is for anyone searching for "PHP extends how to use".

extends creates a new class that carries over the functionality of an existing one. This is called inheritance. It is the classic object-oriented technique of taking a shared "animal" blueprint and adding each animal's own way of making a sound.

The sample code makes Dog inherit from the parent Animal and redefines the speak() method for itself (overriding). The instance created with new Dog("Rex") has both the $name property inherited from Animal and Dog's own speak().

A common stumbling block for beginners is defining a __construct in the child class and forgetting to call parent::__construct(). Miss it and the properties the parent was supposed to set never get initialised.

Leaning on inheritance too heavily can make the relationships between classes overly tangled, so design balance matters. In large applications, the guidance to favour composition over inheritance is widely known.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)