PHP Inheritance
Inheritance lets child classes reuse code from parent classes. It's perfect for creating specialized versions of existing classes without duplicating code!
Output
Click Run to execute your code
Basic Inheritance
<?php
class Animal {
public function makeSound() {
echo "Some sound";
}
}
class Dog extends Animal {
// Inherits makeSound()
}
$dog = new Dog();
$dog->makeSound(); // Works!
?>
Method Overriding
<?php
class Dog extends Animal {
public function makeSound() {
echo "Woof!"; // Override parent method
}
}
?>
Calling Parent Methods
<?php
class Dog extends Animal {
public function makeSound() {
parent::makeSound(); // Call parent version
echo " and Woof!";
}
}
?>
Summary
- extends: Create child class
- Inherit: Get parent's properties/methods
- Override: Replace parent method
- parent:: Call parent method
What's Next?
Next, learn about Abstract Classes - blueprints that can't be instantiated!
Enjoying these tutorials?