Skip to main content
A nullable property in PHP is a class property explicitly declared to accept null as a valid value in addition to its designated data type. Introduced alongside typed properties in PHP 7.4, nullability is enforced by the PHP engine at runtime, ensuring strict type adherence while allowing the absence of a value.

Syntax

Nullability is denoted using either the short-hand question mark prefix (?) or, as of PHP 8.0, a Union Type explicitly including null.

Initialization and State Mechanics

A critical distinction in PHP’s engine is that nullable does not mean implicitly initialized to null. When a typed property (including a nullable one) is declared without a default value, it exists in an uninitialized state. Attempting to read an uninitialized property before assigning a value—even null—will throw a standard Error.
To resolve the uninitialized state, the property must be assigned a value (either of the declared type or null) via a default declaration, a constructor, or direct assignment prior to access.

Inheritance and Type Variance

PHP enforces invariant property types during inheritance. This means a child class cannot alter the nullability of an inherited property. You cannot narrow a nullable property to a non-nullable property, nor can you widen a non-nullable property to a nullable one.

Technical Constraints

  1. The mixed Type: As of PHP 8.0, the mixed pseudo-type inherently includes null. Attempting to declare a property as ?mixed or mixed|null will result in a compile-time fatal error due to redundancy.
  2. Syntax Redundancy: You cannot combine the ? prefix with a union type. Declaring public ?string|int $value; is invalid syntax. You must use public string|int|null $value;.
  3. Untyped Properties: Properties declared without any type (e.g., public $value;) are implicitly nullable and default to null rather than an uninitialized state. The concept of a “nullable property” strictly applies to explicitly typed properties.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More