March 23, 2022

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";