Object-Oriented PHP · Lesson 13 of 14
Static Members
Use static members for behavior or state associated with a class.
Lesson
Static methods and properties belong to the class rather than one particular instance. They can suit pure utility behavior or named constructors, but global mutable static state makes tests and concurrency harder. Prefer instance dependencies when behavior needs configuration or substitution.
This static method is pure: its result depends only on its argument.
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 Static Members. 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
Static Members
PHP
class Slug
{
public static function from(string $title): string
{
return strtolower(str_replace(' ', '-', trim($title)));
}
}
echo Slug::from('PHP Basics');
Expected output
php-basics
Key points
- Use static members for behavior or state associated with a class.
- 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.