Both JavaScript and PHP support inheritance, but their approaches are different.
1. PHP – Class-based inheritance
php
class Animal {
function eat() {
echo "Eating...";
}
}
class Dog extends Animal {
}
$dog = new Dog();
$dog->eat();Animalis the parent class.Dogis the child class.Doginherits methods fromAnimal.
2. JavaScript – Prototype-based inheritance
javascript
const Animal = {
eat() {
console.log("Eating...");
}
};
const Dog = Object.create(Animal);
Dog.eat();Animalis an object.Dogis another object.Animalis the prototype ofDog.Doginherits methods fromAnimal.
Key differences
| PHP | JavaScript |
|---|---|
| Class-based inheritance | Prototype-based inheritance |
extends keyword | Object.create() |
| Parent class | Prototype object |
| Child class | Child object |
| Inheritance between classes | Inheritance between objects |
Final takeaway
In PHP, a class inherits from another class.
In JavaScript, an object can inherit directly from another object through its prototype.
Important: JavaScript also supports class and extends syntax, but internally, inheritance is still based on prototypes.
