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