Constructors and promotion
A constructor gives an object its first values. In PHP it is the __construct() method, and the language can also declare the properties that the constructor fills, so the class stays short.
__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.
<?php class User { public string $name; public function __construct(string $name) { $this->name = $name; } } $user = new User("Ada"); echo $user->name, PHP_EOL;
php construct.php
Ada
The constructor copies the argument into the property, and the object answers with that value afterwards. An object built without the argument is refused before the constructor body runs.
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.
<?php class User { public function __construct(public string $name, public int $score = 0) { } } $user = new User("Ada", 10); echo $user->name, " ", $user->score, PHP_EOL; $guest = new User("Guest"); echo $guest->name, " ", $guest->score, PHP_EOL;
php promotion.php
Ada 10
Guest 0
The two arguments become two public properties, so the arrow reads them without a single assignment line. The second object leaves the score out and starts from the default.
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.
<?php class Config { public function __construct(public string $host = "localhost", public int $port = 3306) { } } $default = new Config(); echo $default->host, ":", $default->port, PHP_EOL; $remote = new Config("db.internal", 5432); echo $remote->host, ":", $remote->port, PHP_EOL;
php defaults.php
localhost:3306
db.internal:5432
The first object takes both defaults, and the second one replaces them in the order of the signature. A caller that needs only the second value writes a named argument, new Config(port: 5432).
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.
<?php class Settings { public function __construct(public readonly string $mode) { } } $settings = new Settings("dark"); echo $settings->mode, PHP_EOL; try { $settings->mode = "light"; } catch (Error $e) { echo $e->getMessage(), PHP_EOL; }
php readonly.php
dark
Cannot modify readonly property Settings::$mode
The first read works and the second write is refused with an Error, which the catch prints. The object keeps its value for its whole life, so code that reads the mode never sees it change.
Exercises
- Add a second required argument to User in construct.php and run the program without it. Which error do you get?
- Rewrite the first example with promotion so that the class body holds no property and no assignment.
- Give Config a named argument call that changes only the port.
- Make Settings readonly and add a method that tries to change the mode from inside the class. Does readonly stop it?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What runs when an object is created with
new?Answer
The
__construct()method of the classThe new keyword creates the object and then calls its constructor, which fills the first values.
-
What does constructor promotion do?
Answer
It declares the property from the parameter and assigns it
A visibility keyword in the signature makes the parameter a property of the object at the same time.
-
Where do optional parameters go in a constructor signature?
Answer
Last, after the required ones
A caller fills arguments from left to right, so an optional one after a required one can be skipped.
-
What does
readonlyallow?Answer
Setting the property once, in the constructor
The constructor writes the value one time, and every later write throws an Error.
-
What does this program print?
<?php class Point { public function __construct(public int $x = 1, public int $y = 2) { } } $point = new Point(y: 7); echo $point->x, $point->y;Answer
17
The named argument fills y, x keeps its default of 1, and the two numbers print side by side.
-
What does this program print?
<?php class User { public function __construct(public string $name, public int $score = 0) { } } $first = new User("Ada", 10); $second = new User("Bob"); echo $first->score, " ", $second->score;Answer
10 0
The first object takes the score of the call and the second one falls back to the default of zero.
-
What does this program print?
<?php class Settings { public function __construct(public readonly string $mode) { } } $settings = new Settings("dark"); try { $settings->mode = "light"; } catch (Error $e) { echo "cannot change"; }Answer
cannot change
The constructor sets the readonly property once; the write after it throws an Error, and the catch prints its line.
-
What does this program print?
<?php class User { public function __construct(public string $name) { } } try { $user = new User(); } catch (ArgumentCountError $e) { echo get_class($e); }Answer
ArgumentCountError
The required argument is missing, so PHP throws an ArgumentCountError before the constructor body runs.
-
What does this program print?
<?php class Config { public function __construct(public string $host = "localhost") { } } $a = new Config(); $b = new Config("db.internal"); echo $a->host, " ", $b->host;Answer
localhost db.internal
The default belongs to the class, so the first object keeps it and the second one takes the argument of its own call.
-
A constructor parameter is promoted with no visibility keyword. What is it?
Answer
Only an argument: no property is created
Promotion needs public, protected, private or readonly in front of the parameter; without one it is a plain argument.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev