Table of Contents
Debugging “Cannot assign null to property” in PHP 8.4 Response Objects
Recently ran into a TypeError that PHP 8.4’s strict typing loves to throw: “Cannot assign null to property OrderResponse::$shippingCost of type float”.
The Setup
You’re consuming a third-party API. Their response sometimes returns null for optional fields. Your response DTO uses strict typed properties:
class OrderResponse
{
public array $items;
public float $shippingCost; // ❌ Problem: not nullable
}
When the API returns {"items": [...], "shippingCost": null}, your JSON deserializer (JMS Serializer, Symfony Serializer, etc.) tries to assign null to a float property. PHP 8.4 says no.
The Fix
Make it nullable:
class OrderResponse
{
public array $items;
public ?float $shippingCost; // ✅ Allows null
}
Don’t Forget Usage Checks
After making a property nullable, audit everywhere you access it:
// Old code (assumes always has value)
$total = $response->basePrice + $response->shippingCost;
// Updated (handles null)
$total = $response->basePrice + ($response->shippingCost ?? 0);
When NOT to Use Nullable
If null isn’t semantically valid (like an exchange rate that defaults to 1.0), set a default value in your deserializer config instead of making the property nullable. Nullable should mean “this value is optional and absence is meaningful,” not “the API is inconsistent.”
Key takeaway: PHP 8.4 strict typing is your friend, but APIs don’t always play nice. Nullable types are the escape hatch – use them intentionally, and always validate assumptions in your code.
Leave a Reply