sort functions – access class member

If you want to sort a class member with the functions uasort, uksort, usort (the u stands for user-defined comparison function) you have to take care of some things.

bool uksort ( array &$array , callable $key_compare_func )

The function takes as first parameter the array you want to sort as reference. Thereby no copy is made to the function stack and any changes are directly made on the origin data. The second parameter is of the type callable – this means you pass a string and php will find the appropriate target (this can be a user function, an object method or static class method).

In my example I will do an object method call. This means I pass an object and the method name to the sort algorithm – this way it can call the sort method of the appropriate object. So it will look like this:

bool uksort ( array &$array , array ( $myObject, 'sortAlgorithm' ) )

Putting it all together:

First I create a new Object of the DataStore – the constructor is called and thereby extract() first. In this function I just create an associative for the member data with a date as key and a dummy value.

Next the sort() function is called which calls uksort. u means: I wan’t to use a custom sort algorithm, k means: I want to sort by the keys only.

The first parameter  $this->data  is the array that should to be sorted. The second parameter a an array array( $this, 'sortByDateDESC' )  that takes the current object – so just $this  and the name of my custom sort algorithm  'sortByDateDESC'  that takes care of the comparison logic.

The output is:

Which is pretty much what we wanted to.

Leave a Reply

Your e-mail address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.