Object-Oriented PHP · Lesson 6 of 14
Constructors
Initialize required object state when constructing an instance.
Lesson
The __construct method runs when an object is created and is the natural place to require its initial dependencies or state. Constructor property promotion can reduce repetition. Reject invalid constructor input so every successfully created object begins in a valid state.
This constructor requires a non-empty title before the object can be used.
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 Constructors. 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
Constructors
PHP
class Article
{
public function __construct(public string $title) {}
}
$article = new Article('Learning PHP');
echo $article->title;
Expected output
Learning PHP
Key points
- Initialize required object state when constructing an instance.
- 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.