Are there any best practices for comparing objects in PHP to detect recursion?

When comparing objects in PHP, detecting recursion can be a common issue, especially when dealing with complex data structures. One way to detect recursion is by keeping track of objects that have already been compared using their memory address. By storing the memory addresses in an array and checking against it during comparisons, you can prevent infinite loops caused by recursive references.

function compareObjects($obj1, $obj2, &$checkedObjects = [])
{
    if (in_array([$obj1, $obj2], $checkedObjects, true)) {
        return true; // Objects are the same and have already been compared
    }

    // Add objects to the checkedObjects array
    $checkedObjects[] = [$obj1, $obj2];

    // Compare properties of the objects
    // Add your comparison logic here

    return false; // Objects are not the same
}