1

I am trying to use this within a class. My compare function is called compare. In a class I would call the function using $this->compare. But, I cannot figure out how to call the class function within usort.

I have tried:

usort($array, this->compare);
usort($array, "this->compare");
usort($array, this->"compare");
usort($array, compare);
usort($array, "compare");

Here is function:

function compare($x, $y)
{
 if ( $x[0] == $y[0] )
  return 0;
 else if ( $x[0] < $y[0] )
  return -1;
 else
  return 1;
}

4 Answers 4

3
usort($array, array($this, 'compare'));

Documented here: http://php.net/manual/en/language.pseudo-types.php#language.types.callback(dead link)

Sign up to request clarification or add additional context in comments.

Comments

1

Have you tried this?

usort($array, array($this, 'compare'))

See PHP's documentation on the callback type.

Comments

1

You do it like this

usort($a, array("InstanceName", "Method"));

You can also send in the instance if you have it, so you can send in $this

usort($a, array($this, "Method"));

A larger code example is in the usort documentation

Comments

0
usort($array, array($this, "compare"));

See: PHP Manual

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.