How can PHP best practices be applied to ensure successful JSON serialization of nested objects?

When serializing nested objects to JSON in PHP, it is important to ensure that all nested objects are properly converted to arrays before serialization. This can be done by implementing a custom serialization method that recursively converts nested objects to arrays. By following this approach, you can ensure successful JSON serialization of nested objects in PHP.

class CustomObject {
    public $nestedObject;

    public function toArray() {
        $data = [
            'nestedObject' => $this->nestedObject->toArray()
        ];
        return $data;
    }
}

class NestedObject {
    public $property;

    public function toArray() {
        return [
            'property' => $this->property
        ];
    }
}

$nested = new NestedObject();
$nested->property = 'value';

$custom = new CustomObject();
$custom->nestedObject = $nested;

$json = json_encode($custom->toArray());
echo $json;