Stewart Robert Hinsley wrote:
Yesterday I prototyped some code to read an XML file, and convert it
into a web page, using the expat XML parser.
I then packaged it into a class, and found that there are problems with
using class member functions as callback functions. In this case calling
xml_set_object() works round the problem.
However, one of the features I want to add is configurable sorting of
the data, using usort() or similar. Am I right in thinking that I can't
use a class member function as a callback function in usort()?
Unfortunately, usort() hasn't been "promoted" to work with objects yet.
If you don't need any other values from the class, Thomas's code will
work quite well. However, sometimes you do need other values - in which
case you have to use a "kludge" of keeping the object in a static member
or global variable. An example of doing it with a static member
variable (a bit long):
<?php
class MyClass { // Showing only necessary code for example
private $sortOrder = 'A'; // (A)scending or (D)escending)
private $myArray = array();
private static $sortObj; // Used to hold the object
function setSortOrder($s) {
if ($s == 'A' || $s == 'D') {
$this->sortOrder = $s;
return true;
}
else
return false;
}
function addElement($e) {
$this->myArray[] = $e;
}
function sort() {
self::$sortObj = $this;
usort($this->myArray, 'mySort');
self::$sortObj = null;
}
function myObjSort($a, $b) {
if ($this->sortOrder == 'A') // Ascending
{
if ($a $b)
return 1;
elseif ($a < $b)
return -1;
else
return 0;
} else {
if ($a < $b)
return 1;
elseif ($a $b)
return -1;
else
return 0;
}
}
static function getSortObject() {
return MyClass::$sortObj;
}
}
function mySort($a, $b) {
return MyClass::getSortObject()->myObjSort($a, $b);
}
$myObj = new MyClass();
$myObj->addElement('4');
$myObj->addElement('2');
$myObj->addElement('10');
$myObj->addElement('5');
$myObj->sort();
print_r($myObj);
$myObj->setSortOrder('D');
$myObj->sort();
print_r($myObj);
?>
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================