Inheritance & Exceptions
Share behaviour between classes, and handle errors gracefully.
What you will learn
- Extend a class with inheritance
- Use access modifiers
- Handle errors with try/catch
Inheritance
Inheritance lets one class build on another. A class can extends another to reuse its properties and methods for free, then add or override its own. The class being extended is the *parent*; the new one is the *child*.
<?php
class Animal {
public function eat() { return "eating"; }
}
class Dog extends Animal {
public function bark() { return "Woof!"; }
}
$d = new Dog();
echo $d->eat(); // inherited: eating
echo $d->bark(); // own: Woof!
?>Dog extends Animal means a Dog automatically gets everything Animal has. So even though Dog only defines bark(), the object $d can still call eat() — it inherited that method from Animal. bark() is its own addition.
Note: Output (in the browser):
eatingWoof!
$d->eat() used the inherited method and $d->bark() used the dog’s own method. Inheritance saves you from rewriting shared behaviour — define it once in the parent.
Note: Access modifiers control visibility: public (anywhere), private (only inside the class), protected (the class and its children). Use private to protect internal data.
Exceptions
An exception is PHP’s way of signalling that something went wrong. You wrap risky code in try; if it fails (a throw happens), control jumps to the catch block instead of crashing the whole page, so you can handle the problem gracefully.
<?php
try {
throw new Exception("Something failed");
} catch (Exception $e) {
echo "Caught: " . $e->getMessage();
}
?>Inside the try, throw new Exception("Something failed") deliberately raises an error. PHP immediately stops the try block and runs the catch, where $e is the exception object. $e->getMessage() pulls out the message we threw, and echo prints it — the script keeps running instead of dying.
Note: Output (in the browser):
Caught: Something failed
Because the error was caught, the page survives. In real apps the try would hold something that *might* fail (like a database connection), and the catch shows a friendly message instead of a fatal crash.
Q. Which keyword makes one class inherit from another?
✍️ Practice
- Create a base
Shapeclass and aCirclethat extends it. - Wrap risky code in try/catch.
🏠 Homework
- Model
Vehicle→Carwith inheritance and a private property.