Inheritance
Last updated
What is Inheritance?
Inheritance, a fundamental concept in object-oriented programming (OOP), is a feature that PHP supports. It lets us create classes which are extensions of other classes, inheriting their methods and properties. This concept allows the creation of more flexible and maintainable code, as it promotes code reuse. For instance, consider we have a 'Vehicle' class and we want to create a 'Car' class. Since cars are a type of vehicle, it would make sense for our 'Car' class to inherit from the 'Vehicle' class.
class Vehicle {
public $color;
function drive() {
echo "Driving...";
}
}
class Car extends Vehicle {
function horn() {
echo "Beeping...";
}
}
$myCar = new Car();
$myCar->drive(); // Inherits drive method from Vehicle
$myCar->horn(); // Unique to Car
In the above example, the 'Car' class inherits the drive method from the 'Vehicle' class but also has an additional method, horn. This is an illustration of how inheritance in PHP can help to organize your code efficiently and intuitively.
Free resources to learn Inheritance
- Official docsInheritance
More in stage 11: OOP Fundamentals
- OOP Fundamentals
- Classes and Objects
- Constructor / Destructor
- Properties and Methods
- Access Specifiers
- Static Methods and Properties
- Input Validation
- SQL Injection
- XSS Prevention
- CSRF Protection
- Password Hashing
- Auth Mechanisms
- Sanitization Techniques
- PDO
- MySQLi
- Object-Relational Mapping (ORM)
- Database Transactions
- Connection Pooling
- Performance Optimization
- Database Migrations
Inheritance: common questions
Can I learn Inheritance in Hindi?
This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Inheritance in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.
Is this Inheritance tutorial for beginners?
It is lesson 66 of 120 in the free PHP roadmap, in stage 11, OOP Fundamentals. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.