Click to See Complete Forum and Search --> : usort() with callback in a class...


Znupi
09-23-2007, 10:56 AM
I am creating a simple CMS.
Here's the situation: I have an array which looks like:

Array
(
[0] => Array
(
[name] => download
[size] => [dir]
[href] => ?action=browse&f=&p=download/
)

[1] => Array
(
[name] => files
[size] => [dir]
[href] => ?action=browse&f=&p=files/
)

[2] => Array
(
[name] => images
[size] => [dir]
[href] => ?action=browse&f=&p=images/
)
)

And I want to sort it by name. So I wrote this function and put it inside the main class named CMSEngine:

function cb_sort($a, $b) {
return strcasecmp($a['name'], $b['name']);
}

And then tried all of these combinations, but none worked:

usort($aDirs, CMSEngine::cb_sort);
usort($aDirs, $this->cb_sort); // Yes, this happens inside another function in the same class.
usort($aDirs, "CMSEngine::cb_sort");
usort($aDirs, "$this->cb_sort");
usort($aDirs, "\$this->cb_sort");

Is there any way to do this?

bokeh
09-23-2007, 11:28 AM
A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1.
usort($aDirs, array($this,'cb_sort')); // Called from another function in the same class.
usort($aDirs, array($obj,'cb_sort')); // Called from procedural code (outside the class).

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0.
usort($aDirs, array('ClassNameHere','cb_sort'));

Znupi
09-23-2007, 02:26 PM
Oh yeah, I didn't scroll that down on the usort manual page :P, thanks! :)

bokeh
09-23-2007, 02:43 PM
Maybe you would have had better luck with the manual if you had thought what you were trying to extract from it. Your question was about callback syntax (http://www.php.net/callback), not usort.

Znupi
09-23-2007, 03:43 PM
Good info, thanks again :)