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
Concept | Override | Overwrite |
---|---|---|
Used with | Inheritance (methods in classes) | Variables, arrays, files, etc. |
Context | OOP (Object-Oriented Programming) | General programming (not just OOP) |
Meaning | Child class changes parent method | New value replaces old value |
Example | ChildClass::sayHello() changes behavior | $x = "old"; $x = "new"; |
Comments are closed.