Sorting an array of objects in PHP
<p>I want to write a static method in a class to generically sort an array of objects.</p>

<p>I am thinking of somthing along the lines of:</p>

<pre><code>class GenUtils {
  const ASCENDING = 1;
  const DESCENDING = 2;

  protected static alphaSort($value1, $value2, $sort_type=self::DESCENDING){
     $retval = strcasecmp($value1, $value2);
     return ($sort_type == self::DESCENDING) ? $retval : (-1*$retval);
  }

  protected static numericSort($value1, $value2, $sort_type=self::DESCENDING){
    return  $value1 &lt; $value2;
  }

  // Assumption: array is non-empty and homogeneous
  public doSort(array&amp; $object_array, $method_name, $sort_type=self::DESCENDING) {
        if(!empty($object_array) &amp;&amp; method_exists($object_array[0],$method_name)) {
          $element = $object_array[0];
          $value = $element-&gt;$method_name();
          if(is_string($value)){
            //do string sort (possibly using usort)
          }
          elseif(is_number($value)){
            //do numeric sort (possibly using usort)
          }
        }
  }
}
</code></pre>

<p>This is just a quick brain dump -perharps someone can fill in the missing pieces, or suggest a better way of doing this?</p>

<p><strong>[Edit]</strong>
Just to clarify, the objects to be sorted (in the array), have methods which return either a string (e.g. getName()) or a numeric value (e.g. getId())</p>

<p>A typical usecase code snippet would therefore be somethimng like this:</p>

<pre><code>GenUtils::doSort($objects,'getName'); // This will do an alphabetic DESC sort using the getName() method

GenUtils::doSort($objects, 'getId', GenUtils::ASCENDING); // This will do a numeric ASC sort using the getId() method
</code></pre>
