Skip to main content
An optional parameter in PHP is a function or method parameter initialized with a default value in the declaration signature. If the caller omits the corresponding argument during invocation, the PHP engine automatically binds the parameter to its default value, preventing an ArgumentCountError.

Syntax

Optional parameters are defined using the assignment operator (=) directly within the parameter list.

Lexical Rules and Constraints

1. Parameter Ordering Optional parameters must be positioned sequentially at the end of the parameter list. Declaring a required parameter after an optional parameter breaks positional argument resolution and, as of PHP 8.0, triggers a Deprecated notice.
2. Constant Expression Requirement The default value must evaluate to a constant expression at compile time. It cannot be a variable, a class property, or a standard function call. Allowed types include scalars (integers, floats, strings, booleans), arrays, and null.
3. Object Initializers (PHP 8.1+) Starting with PHP 8.1, the new keyword can be used within parameter declarations to instantiate objects as default values.

Type System Interactions

Implicit vs. Explicit Nullability Assigning null as a default value historically made a parameter implicitly nullable. Modern PHP strictly requires explicit nullability using the ? prefix or union types to maintain strict type safety and avoid deprecation warnings in newer versions.
Named Arguments (PHP 8.0+) With the introduction of named arguments, the strict positional requirement during invocation is bypassed. Developers can skip optional parameters regardless of their position in the signature by explicitly targeting the parameter names.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More