tags:

views:

60

answers:

1

Long story short, I need to sort an array of objects using usort, and I need to tell usort which fields in the objects to sort by.

The obvious solution is to create tens of separate usort sorting functions, but this seems sort of redundant and ugly. Most of the time, objects will be sorted by input from $_GET, but not always, so I don't want to sort by $_GET variables directly.

Is it possible for the usort function to use the current class' sorting function? Something like this

<?php

    class myClass
    {
        public $myArray;
        private $by;

        public function filter($by)
        {
            $this->by = $by;
            usort($this->myArray, /* Somehow point to the following function: */ );
        }

        private function srt($a, $b)
        {
            $c = $this->by; // <- reaching a third variable

            // ...
        }
    }

?>
+2  A: 

Yes, pass an array of the object and the method name to usort():

usort($this->myArray, array($this, 'srt'));

EDIT: I've tested and found that this will work with private methods as long as you call usort() in the same class that contains the private method.

BoltClock
+1. Very good idea.
Alexander.Plutov