Object-Oriented PHP · Lesson 8 of 14
Inheritance
Extend a base class only when the subtype can honor its contract.
Lesson
Inheritance lets a child class reuse or specialize behavior from a parent. Use it for a genuine is-a relationship, not merely to share a few lines. Prefer composition when behavior can be delegated, because deep inheritance chains make changes harder to reason about.
The child inherits a stable method and adds one focused capability.
Further guidance
Give an object one clear responsibility and protect state that must satisfy a rule. Prefer a small public contract and composition for replaceable collaborators; use inheritance only for a genuine subtype. Test behavior through public methods instead of relying on internal implementation details.
Practice task: Create a fresh example for Inheritance. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
Inheritance
PHP
class Message
{
public function text(): string { return 'Hello'; }
}
class WelcomeMessage extends Message {}
echo (new WelcomeMessage())->text();
Expected output
Hello
Key points
- Extend a base class only when the subtype can honor its contract.
- Protect object invariants behind a small public API.
- Prefer composition unless inheritance expresses a genuine subtype.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.