Archive - Originally posted on "The Horse's Mouth" - 2008-10-04 05:47:07 - Graham Ellis
The OO model in PHP is very powerful indeed - and much more code is now written using the facilities it offers than was the case a year or two ago. On yesterday's Object Oriented Programming in PHP course, I wrote a new example that nicely brought together many of the facilities on offer - you can see the full sample code here.
One very common requirement is to sort an array of objects in PHP, and if you just use the regular sort function, you'll end up sorting (I think) based on the memory address at which they are held. That is never what you want! Instead - you should use usort
Here's my example of a call to usort:
usort($wellhousemanor,array("transact","mvf"));
And that sorts an array of objects in the $wellhousemanor array, using the static member function called mvf in the class transact to compare pairs of records. All you (as the application programmer) need do is make the call in this (rather curious, it must be said) way. If you're the programmer writing the class, you simply provide a method of the given name that takes two parameters and return negative if the first object passed should come earlier, positive if the second object passed should come earlier, and zero to indicate that the objects are equally ranked for sorting.
Here's my example comparator:
static function mvf($first,$second) {
if ($first->getvalue() > $second->getvalue()) return 1;
if ($first->getvalue() < $second->getvalue()) return -1;
return 0;
}
Q: I'm a PHP programmer - should I use objects these days?
A: In most cases YES - exceptions are minimum maintainance jobs on older code, and tiny applications where you'll never have more than a few lines of PHP. And even if you're not writing your own objects, chances are that you'll use objects that other people have written and perhaps contributed via something like PEAR.