Default value for property of type %s may not be null. Use the nullable type %s to allow null default value

Description

Typed properties can have a default value, but that default value must match the declared type. null is only a valid default when the type is explicitly nullable, written with a leading ?, such as ?int.

Without the ?, a scalar or class type like int or X does not accept null, even as a default value that is never read before being overwritten.

Example

<?php

class X
{
    public int $value = null;
}

?>

Literal Examples

  • Default value for property of type int may not be null. Use the nullable type ?int to allow null default value

Solutions

  • Make the property type nullable, for example ?int instead of int.

  • Remove the default value, and initialize the property in the constructor instead.

  • Use a non-null default value that matches the declared type.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See ` <https://php-changed-behaviors.readthedocs.io/en/latest/behavior/.html>`_.