Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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.
class Entity {
    // PHP 7.4+ syntax
    public ?string $shortHandNullable;
    
    // PHP 8.0+ Union Type syntax
    public string|null $unionNullable;
}

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.
class User {
    public ?string $uninitializedName;
    public ?string $initializedName = null;
}

$user = new User();

// Valid: Property was explicitly initialized to null
var_dump($user->initializedName); // Outputs: NULL

// Fatal Error: Typed property User::$uninitializedName must not be accessed before initialization
var_dump($user->uninitializedName); 
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.
class ParentClass {
    public ?string $identifier;
}

class ChildClass extends ParentClass {
    // Fatal error: Type of ChildClass::$identifier must be ?string (as in class ParentClass)
    public string $identifier; 
}

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.
Master PHP with Deep Grasping Methodology!Learn More