SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Nov 2004
    Location
    New Jersey
    Posts
    317
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Calling comparison functions that are defined within classes?

    I'd like to call a comparison function that's defined within a class in static fashion, in PHP4. Example code:
    Code:
    $array = array(100, 40, 120, 125, 110, 60);
    usort($array, Test::cmp_function);
    //$test = new Test();
    //usort($array, $test->cmp_function);
    print_r($array);
    
    class Test {
    	function cmp_function($a, $b) {
    		return ($a>$b);
    	}
    }
    Trying to call the function with Test::cmp_function however gives the error Parse error: syntax error, unexpected ')', expecting '('. And commenting that line out and uncommenting the object-oriented lines gives the warning Warning: usort() [function.usort]: Invalid comparison function.

    How can I call the Test::cmp_function comparison function?

  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    A callback can either be a string containing the function name, or an array - the first item being the class/object, the second being the method.

    PHP Code:
    usort($array, array($test'cmp_function')); 
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  3. #3
    SitePoint Addict
    Join Date
    Nov 2004
    Location
    New Jersey
    Posts
    317
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you very much, that works


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •