TypeError: Argument #1 ($param) must be of type string, null given
ID: php/type-error-argument
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 83 | active | — | — | — |
Root Cause
TypeErrors for function arguments became more common in PHP 8.x due to stricter type enforcement. Passing null to a non-nullable parameter, passing wrong scalar types with strict_types=1, or passing incorrect object types all trigger this error.
genericWorkarounds
-
92% success Make the parameter nullable or provide a default value when null is a valid input
If null is a legitimate value, change the type hint to nullable: 'function process(?string $param)' or provide a default: 'function process(string $param = "")'. Update the function body to handle the null case appropriately.
-
90% success Fix the caller to pass the correct type by validating data earlier in the pipeline
Trace back to where the incorrect value originates. Add validation at the source (form input, API response, database result) to ensure correct types before the data reaches the function. Use null coalescing or type conversion at the appropriate boundary.
Dead Ends
Common approaches that don't work:
-
Removing type declarations from function signatures to avoid the error
80% fail
Removing type hints eliminates the safety net that type checking provides. The function may still fail downstream with harder-to-debug errors when receiving unexpected types. This also degrades IDE support and static analysis.
-
Casting all arguments blindly before passing them
65% fail
Blindly casting (e.g., (string)$value) can produce incorrect results. Casting null to string gives empty string, casting an object to int gives 1, and casting an array to string triggers another error. The actual data flow issue is hidden.