title: Compare objects on equality in PHP
body: <p><strong>Specifics</strong></p>
  
  <p>First, the definition of "equality" in my case is - that objects are equal when they have same structure and values for that structure. However, they may be not same instance, or properties may be not in same "order" (I mean, as they were assigned/defined). There are similar questions here on SO, like <a href="https://stackoverflow.com/questions/5911067/compare-object-properties-and-show-diff-in-php">this</a> - but they are not covering my case.</p>
  
  <p>I need to compare entities in PHP due to testing of my code purposes - and those entities might be anything. In particular, they may be objects. <a href="http://php.net/manual/en/language.oop5.object-comparison.php" rel="nofollow noreferrer">Objects comparison</a>, however, is not "safe". Imagine that you are comparing:</p>
  
  <pre><code>$result = $objectX == $objectY;
  </code></pre>
  
  <p>And this may lead to fatal error in case when objects have circular references. Simple example for it I prepared <a href="http://3v4l.org/6Huqf" rel="nofollow noreferrer">here</a>. As we can see, PHP tries to follow nested levels and fails in infinite loop - because by nature objects are same in content, but have circular references.</p>
  
  <p>Important detail is that objects might contain non-serializable stuff (like closures), which makes impossible to rely on "seralize/unserialize" approach (even if to forget about unordered comparison)</p>
  
  <p><strong>Current approach</strong></p>
  
  <p>I have the code like <a href="http://3v4l.org/UNsj6" rel="nofollow noreferrer">this</a> (quite too much to paste directly here, but just in case, here is a <a href="https://gist.github.com/almadomundo/0ec0dce7f5435368aec0" rel="nofollow noreferrer">gist</a>) - so I am performing <a href="http://en.wikipedia.org/wiki/Depth-first_search" rel="nofollow noreferrer">DFS</a> there and catching situations with such circular references. As you can see, it's quite complex - and, by the way, it is slow.</p>
  
  <p>Another issue with current approach is - that when there are arrays inside objects, they will be compared with respect of elements order, which, in some cases, is not fine for me (ideal case - when I'll be able to switch order-wise comparison), but to overcome it natively, I probably will need to "sort" arrays somehow - and I have no idea how to do that - as, again, comparison of those arrays elements will not be safe.</p>
  
  <p>And, more, circular arrays references will also cause failure:</p>
  
  <pre><code>$array = ['foo', $object, &amp;$array];
  </code></pre>
  
  <p><strong>Question</strong></p>
  
  <p>What could be other (better) approaches to resolve a matter? Serializing objects might be the case, but due to non-ordered set of properties it will fail for me. </p>