Why This Happens
json_encode() cannot handle objects or arrays that reference themselves, creating an infinite loop. This happens with parent-child relationships where a child references its parent, Doctrine entities with bidirectional associations, or tree structures with back-references.
The Problem
class Category {
public string $name;
public ?Category $parent = null;
public array $children = [];
}
$parent = new Category();
$parent->name = 'Root';
$child = new Category();
$child->name = 'Sub';
$child->parent = $parent; // Circular!
$parent->children[] = $child;
echo json_encode($parent); // Recursion detectedThe Fix
class Category implements JsonSerializable {
public string $name;
public ?Category $parent = null;
public array $children = [];
public function jsonSerialize(): mixed {
return [
'name' => $this->name,
'children' => $this->children, // Don't include parent
];
}
}Step-by-Step Fix
- 1
Find the circular reference
Identify which objects reference each other in a cycle. Look for parent-child, bidirectional, or self-referencing relationships.
- 2
Implement JsonSerializable
Have the class implement JsonSerializable and define jsonSerialize() to return only the properties needed, excluding back-references.
- 3
Use a serialization library
For complex object graphs, use a serialization library like Symfony Serializer that supports circular reference handling.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free