Comparing Objects with PHP

Yesterday, I was working on PHPAlgorithms (again). When trying to implement Graphs (Directed and Undirected), I found out that a node could not be found in the graph although I was sure it was there. After a lot of debugging and reverse engineering, I found out that:

  • the adjacency list, which contains all adjacent nodes changes over time
  • a newly added node has no adjacent nodes
  • PHP’s == and/or === are not designed to handle this circumstances

When comparing two objects, there are two possibilities:

  • == which checks if two instances are from the same class and have the same values
  • === which checks if two instances are exactly the same instance

Considering that a Node instance has a adjacency list which contains all adjacent Node instances, both comparisons return false.

What is about Comparables?

There is a rfc for implementing the Comparable interface – since 2010. That is why I have decided to implement my own tiny Comparable interface/method. In addition, a Comparator object which compares two variables was also necessary. The Comparator class gets two variables and checks first if they implement the Comparable interface. If this is the case, the compareTo() method is called and the result is returned. If this is not the case, a “regular” comparison (===) is performed.

Is this a good solution?

Unfortunately not. Implementing such a basic function is usually the task of the programming language. Doing this by hand is a potential source of bugs which costs a lot of time to fix. This time may used for concentrating on your main tasks.

However, PHP does not provide an effective way of comparing two objects. As long as this is the case – the rfc shows that this will be the case for a very long time to come – I see no other way to do it better.

last update: 07/09/18 12:48:20. Change Description: The source code was formatted for readability

picture taken from GoodWorks.

 

Leave a Comment