Php features: constructor changes

RMAG news

After attributes and first-class callable syntax I got the idea to bundle the method parameter improvements.

Theory

Php 8.0 constructor property promotion.
Php 8.1 introduced new in initializers.

Constructor property promotion makes it easier to create classes without repetition. While new in initializers is more geared to attributes, specifically to allow nested attributes

Code

class A{
function __constructor(public string $b, private $c = new C()) {}
}

Before you had to write it like this

class A {
public string $b;
private $c;

function __constructor(string $b) {
$this->b = $b;
$this->c = new C();
}
}

Which is more verbose.

I don’t recommend to use the initializer, because the tests will have to be at least integration tests. But it is good to know that it is possible.

In php 8.0 If you wanted nested attributes you had do something like this

#[Validators(
[‘password’ => [
‘required’,
‘minLength’ => 8
]]
)]

Now you can do

#[Validators(
[‘password’ => [
new Required(),
new MinLength(8)
]]
)]

While it doesn’t change much for the example code. It makes the code less error prone because a typo will be discovered sooner. And an IDE will autocomplete the attribute for you.
When the attributes have multiple parameters you can also use named parameters, but that is for a another post.

Leave a Reply

Your email address will not be published. Required fields are marked *