Basic Inheritance
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 21 of 91.
Inheritance allows a class to acquire properties and methods from another class. Instead of rewriting the same code, you can create a base class with shared functionality and have other classes inherit from it.
The class being inherited from is called the parent class (or base class), and the class that inherits is called the child class. You use the extends keyword to establish this relationship:
<?php
class Animal {
public $name;
public function __construct($name) {
this->name = $name;
}
public function speak() {
return "$this->name makes a sound";
}
}
class Dog extends Animal {
public function fetch() {
return "$this->name fetches the ball";
}
}
$dog = new Dog("Buddy");
echo $dog->speak() . "\n";
echo $dog->fetch();
Output:
Buddy makes a sound
Buddy fetches the ballThe Dog class automatically has access to the $name property, the constructor, and the speak() method from Animal. It also defines its own fetch() method that only dogs have.
This creates a clear hierarchy: every dog is an animal, so it makes sense for Dog to inherit from Animal. The child class can use everything from the parent while adding its own specialized behavior.
Key Point: Inheritance promotes code reuse and establishes logical relationships between classes. The child class inherits all public and protected members from the parent, reducing duplication and making your code easier to maintain.
Challenge
EasyLet's build a vehicle hierarchy system that demonstrates how inheritance allows child classes to share functionality from a parent class while adding their own specialized behaviors.
You'll organize your code across three files:
Vehicle.php— Define aVehicleclass that serves as the parent for all vehicles. It should have a public$brandproperty and a constructor that accepts and sets the brand. Include astart()method that returns"[brand] is starting"and astop()method that returns"[brand] is stopping".Motorcycle.php— Define aMotorcycleclass that extendsVehicle. Include the Vehicle file at the top. The Motorcycle class doesn't need its own constructor since it will inherit the parent's constructor. Add awheelie()method that returns"[brand] is doing a wheelie!"— this is a behavior unique to motorcycles.main.php— Include the Motorcycle file (which already includes Vehicle). You'll receive one input: the motorcycle brand. Create aMotorcycleobject with this brand. Print the result of callingstart(), thenwheelie(), thenstop(), each on its own line.
Notice how the Motorcycle class automatically inherits the $brand property, the constructor, and both the start() and stop() methods from Vehicle. The child class only needs to define what makes it unique — in this case, the ability to do a wheelie. This is the power of inheritance: write common functionality once in the parent, and let children reuse it while adding their own specializations.
Cheat sheet
Inheritance allows a class to acquire properties and methods from another class using the extends keyword. The class being inherited from is called the parent class (or base class), and the class that inherits is called the child class.
<?php
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function speak() {
return "$this->name makes a sound";
}
}
class Dog extends Animal {
public function fetch() {
return "$this->name fetches the ball";
}
}
$dog = new Dog("Buddy");
echo $dog->speak(); // Buddy makes a sound
echo $dog->fetch(); // Buddy fetches the ball
The child class inherits all public and protected members from the parent, including properties, constructors, and methods. The child can also add its own specialized methods and properties.
Inheritance promotes code reuse and establishes logical relationships between classes, reducing duplication and making code easier to maintain.
Try it yourself
<?php
// Include the Motorcycle class (which already includes Vehicle)
require_once 'Motorcycle.php';
// Read input
$brand = trim(fgets(STDIN));
// TODO: Create a Motorcycle object with the brand
// TODO: Print the result of start()
// TODO: Print the result of wheelie()
// TODO: Print the result of stop()
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern