PHP 8 constructor promotion with inheritance (subclasses)

Guy Thomas
2 min readMay 10, 2023

--

PHP 8 has this amazing feature called “constructor promotion” that allows you to define the properties of a class and set them in one go via the constructor. This removes a lot of boilerplate. However, how do we create a subclass which defines additional properties?

Here we have the base class that we want to extend:

<?php

class User {
public function __construct(
public string $username,
public string $firstname,
public string $lastname
) {}
}

Here is a subclass which adds a token, and unix timestamp to the user model.

<?php

class UserWithToken extends User {
public function __construct(
public string $token,
public int $loginTime,
...$args) {
parent::__construct(...$args);
}
}

Note that the spread operator (…) on $args basically takes the rest of the arguments passed into the constructor and allows us to pass them back on up to the base class constructor(User).

Now we can instantiate our userWithToken as follows:

<?php

$username = 'Guy.Thomas';
$firstname = 'Guy';
$lastname = 'Thomas';
$authtoken = uniqid();
$userWithToken = new UserWithToken($authtoken, time(),
$username, $firstname, $lastname);

Notice how the only drawback is that the subclass properties have to be defined first.

If you don’t like the order in which the arguments are passed, you can get around this by using named arguments:

<?php

$username = 'Guy.Thomas';
$firstname = 'Guy';
$lastname = 'Thomas';
$authtoken = uniqid();
$userWithToken = new UserWithToken(...[
'username' => $username,
'firstname' => $firstname,
'lastname' => $lastname,
'authtoken' => $authtoken,
'loginTime' => time()
]);

Since the arguments are named, the order doesn’t matter!

You can see this in action here:

Conclusion — constructor promotion works great with sub classes!

--

--

Guy Thomas
Guy Thomas

Written by Guy Thomas

Musician, Screen writer, Coder.

No responses yet