JavaScript Prototype vs PHP Inheritance

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();
  • Animal is the parent class.
  • Dog is the child class.
  • Dog inherits methods from Animal.

2. JavaScript – Prototype-based inheritance

javascript

const Animal = {
    eat() {
        console.log("Eating...");
    }
};

const Dog = Object.create(Animal);

Dog.eat();
  • Animal is an object.
  • Dog is another object.
  • Animal is the prototype of Dog.
  • Dog inherits methods from Animal.

Key differences

PHPJavaScript
Class-based inheritancePrototype-based inheritance
extends keywordObject.create()
Parent classPrototype object
Child classChild object
Inheritance between classesInheritance 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.