Question

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

            // ...
        }
    }

?>
Was it helpful?

Solution

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.

OTHER TIPS

Other ways you can call usort function from inside a method.

usort($this->myArray, 'myClass::srt');
usort($this->myArray, array(self::class, 'srt'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top