Jump to content

[SOLVED] Defining usort callback function when it is another method of a class


Recommended Posts

Does anyone know if it is possible to set the callback function of a user defined sort as another method of a class?

 

That might be a poor explanation, so perhaps some code will help to clarify:

 

<?php
class myclass{
    function mysort($a,$b){
        return $a - $b;
    }
    function pointlessfunction(){
        $array = array(4,3,1,4,5,7,2);
        usort($array,'mysort');//this is the problem
    }
}
$myclass = new myclass();
$myclass->pointlessfunction();
?>

 

The above gives an 'invalid comparison function' error, which is fair enough - normally when referencing functions in the same class, you use $this. However, i've tried the above with various replacements like:

 

usort($array,'this->mysort');
//or
usort($array,$this->mysort);

 

Without success. I realise that i could move the mysort function outside of the class, but i was wondering if it is possible to keep it within?

 

I hope that's clear enough. Thanks in advance for any help.

 

Ben

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.