Worst interface ever: PHP's version_compare()

The “Worst interface ever” title goes to version_compare().

If you pass two versions to version_compare() it acts as <=> operator: returns either -1, 0 or 1, which is totally understandable and reasonable. Even if it is machine-oriented, because this function is designed for the callback-based sorting.

However when you pass a third optional $operator parameter, it will change the functions behavior so that it returns TRUE or FALSE depending on the comparison result.

Would you guess if this call will return TRUE or FALSE?

1
version_compare('2.0.1', '1.5.4', '<')

Does it correspond to 2.0.1 < 1.5.4 or to 1.5.4 < 2.0.1?

Conclusions:

  1. Don’t add optional parameters to change the function behavior. Create new interface instead.

  2. Make interfaces for humans. This leaves no doubts:

    1
    version_compare('2.0.1', '<', '1.5.4')
  3. Use value-objects if possible, overloading the comparison operator for the specific types:

    1
    new Version('2.0.1') < new Version('1.5.4')