June 23, 2025

Difference between Override and Overwrite

Override

Definition:
When a child class provides a new version of a method inherited from a parent class, this is called method overriding.

šŸ”§ Example:

class ParentClass {
    public function sayHello() {
        echo "Hello from Parent";
    }
}

class ChildClass extends ParentClass {
    public function sayHello() {
        echo "Hello from Child"; // override parent method
    }
}

$obj = new ChildClass();
$obj->sayHello();  // Output: Hello from Child

āœ… Override happens only with inherited methods (from parent class).

🧠 Think of it as:

ā€œI’m a child class, and I want to change how this method behaves.ā€


āœ… 2. Overwrite

Definition:
This usually means replacing an existing value (variable, file, etc.) — not limited to classes.

šŸ”§ Example 1: Overwriting a variable

$name = "John";
$name = "Alice";  // Overwrite the previous value
echo $name;       // Output: Alice

šŸ”§ Example 2: Overwriting a file

file_put_contents("log.txt", "New Content");  // Overwrites the file

āœ… Overwrite means replacing any existing value — it can be a variable, array, file content, etc.

🧠 Think of it as:

ā€œI’m replacing something that already existed.ā€


šŸ†š Summary Table

ConceptOverrideOverwrite
Used withInheritance (methods in classes)Variables, arrays, files, etc.
ContextOOP (Object-Oriented Programming)General programming (not just OOP)
MeaningChild class changes parent methodNew value replaces old value
ExampleChildClass::sayHello() changes behavior$x = "old"; $x = "new";