Constructors and promotion
| __construct | |
| Constructor promotion | |
| Default values | |
| Readonly properties |
__construct
The __construct method runs once when an object is created with new. Use it to require important data up front.
Assign each argument to a property so the object starts in a valid state.
class User { public string $name; public function __construct(string $name) { $this->name = $name; } }
Constructor promotion
Promotion declares properties right in the constructor signature. It removes repeated property lines and assignments.
Add visibility before each promoted argument and PHP creates the property for you.
class User { public function __construct(public string $name, public int $score = 0) { } }
Default values
Default values make arguments optional. Callers may skip them when the standard value fits.
Keep required arguments first and optional ones last so calls stay readable.
class Config { public function __construct(public string $host = "localhost", public int $port = 3306) { } }
Readonly properties
A readonly property can be set once and never changed after. It protects values like mode flags and identifiers.
Combine readonly with promotion for short and safe value objects.
class Settings { public function __construct(public readonly string $mode) { } }
Next: Inheritance
Article author: Arthur Isaev