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 parameter in PHP is a type declaration that explicitly permits a function or method argument to accept either a specified data type or the null value. It modifies the type signature to bypass strict type enforcement exclusively for null, preventing a TypeError exception when an absence of value is passed to the routine.

Syntax and Implementation

PHP provides two primary syntactic constructs for defining nullable parameters, depending on the PHP version. 1. The Nullable Prefix Operator (?) Introduced in PHP 7.1, prefixing a type declaration with a question mark explicitly marks it as nullable.
function processString(?string $input): void {
    var_dump($input);
}

processString("Data"); // string(4) "Data"
processString(null);   // NULL
2. Union Types (|null) Introduced in PHP 8.0, the union type syntax allows null to be appended to one or more types. At the engine level, ?Type is internally resolved as Type|null.
function processInteger(int|null $input): void {
    var_dump($input);
}

// Combined with multiple types
function processMixed(string|int|null $input): void {
    var_dump($input);
}

Explicit vs. Implicit Nullability

Historically, PHP allowed implicit nullability by assigning null as the default value to a strictly typed parameter.
// Implicit nullability (Deprecated as of PHP 8.4)
function legacyProcess(string $input = null): void {}
Modern PHP standards require explicit nullability. If a parameter has a default value of null, the type declaration itself must explicitly include the nullable operator or union type.
// Explicit nullability with a default value (Standard)
function modernProcess(?string $input = null): void {}
function modernUnionProcess(string|null $input = null): void {}

Interaction with Strict Typing

When declare(strict_types=1); is active, nullable parameters enforce exact type matching. The PHP engine will not coerce falsy values (such as false, 0, or "") into null. The argument passed must strictly evaluate to the declared type or exactly null.
declare(strict_types=1);

function evaluateState(?bool $state): void {}

evaluateState(true);  // Valid
evaluateState(null);  // Valid
evaluateState(0);     // Fatal error: Uncaught TypeError

Variadic Nullable Parameters

When applying nullability to variadic parameters (...), the nullability applies to the individual elements within the unpacked array, not the array itself.
function processVariadic(?string ...$inputs): void {
    // $inputs is evaluated as array<int, string|null>
}

processVariadic("A", null, "B"); // Valid
Master PHP with Deep Grasping Methodology!Learn More