Skip to main content
There are a few ways to define default values for a data object. Since a data object is just a regular PHP class, you can use the constructor to set default values:
This works for simple types like strings, integers, floats, booleans, enums and arrays.

Complex Default Values

But what if you want to set a default value for a more complex type like a CarbonImmutable object? You can use the constructor to do this:
You can now do the following:

Default Values with Validation

Even validation will work:

Requirements for Complex Defaults

There are a few conditions for this approach:
1

Use a sole property

You must always use a sole property, a property within the constructor definition won’t work
2

Add Optional type (recommended)

The optional type is technically not required, but it’s a good idea to use it otherwise the validation won’t work
3

Ensure valid defaults

Validation won’t be performed on the default value, so make sure it is valid