R
R
Ruslan Leviev2011-04-28 21:41:00
PHP
Ruslan Leviev, 2011-04-28 21:41:00

PHP: Calling a custom sort function from an object?

In PHP there is such a function: The name of the function that will take the next pair of values ​​​​and compare them is passed to it as the second parameter. There is a regular PHP class:
bool usort ( array &array, callback cmp_function )

namespace MyProj;

class Test {
  public function sortDir($a,$b)
  {
    if(is_dir($a['path']) && !is_dir($b['path'])) return -1;
    if(!is_dir($a['path']) && is_dir($b['path'])) return 1;
    if($a['name']<$b['name']) return -1; elseif($a['name']>$b['name']) return 1; else return 0;
  }
  
  public function getList()
  {
    $dir[0] = array('path' => '/home/www', 'name' => 'www');
    $dir[1] = array('path' => '/home/www/css', 'name' => 'css');
    $dir[2] = array('path' => '/home/www/test.txt', 'name' => 'test.txt');
    $dir[3] = array('path' => '/home/www/css/main.css', 'name' => 'main.css');
    
    usort($dir, 'sortDir');
  }
}

$obj = new Test();
$obj->getList();

Here's how to correctly call <b>usort($dir, 'sortDir')</b>in one of the last lines? What options I have not tried, it always gives out:
Warning: usort() expects parameter 2 to be a valid callback, function 'sortDir' not found or invalid function name

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
skvot, 2011-04-28
@skvot

usort($a, array("Test", "sortDir"));

N
niko83, 2011-04-28
@niko83

documentation to help
www.php.net/manual/en/language.pseudo-types.php#language.types.callback

R
ramilexe, 2011-04-28
@ramilexe

Try
usort($dir, array("this", "sortDir"));
or
usort($dir, array("Test", "sortDir") );

K
Krio, 2011-04-29
@Krio

usort($dir, array($this, "sortDir") );

W
WebSpider, 2011-04-28
@WebSpider

usort($dir, 'self::sortDir');
or
usort($dir, 'MyProj\Test::sortDir');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question