Andrei Stalbe
Andrei Stalbe

Reputation: 1531

PHP Notice: Object of class Closure could not be converted to int

I'm getting a strange warning notice in my application. I'm using a custom usort function inside a class. This is how it looks:

class Class_Name
{
    function zstream_builder()
    {
            $array = some_array();
        //sort posts by date DESC
        usort($array, array('Class_Name', 'zstream_sorter')); // <- the notice is thrown on this line

        return $array;
    }

    private static function zstream_sorter($key = 'sort_str_date')
    {
        return function ($a, $b) use ($key)
        {
            return strnatcmp($a[$key], $b[$key]);
        };
    }
}

this is the notice I get:

Notice: Object of class Closure could not be converted to int in PATH_TO_FILE on line xx

any ideas?

Upvotes: 3

Views: 3163

Answers (2)

jaudette
jaudette

Reputation: 2303

Your compare function needs to return an int, not a function.

If you want to select your sort field, you should use

protected $key = 'sort_str_date';

function zstream_builder()
{
  $array = some_array();
  //sort posts by date DESC
  usort($array, array($this, 'z_sorter')); 

  return $array;
}

function z_sorter($a, $b) 
{
   return strnatcmp($a[$this->key], $b[$this->key]);
}

Upvotes: 1

deceze
deceze

Reputation: 522412

usort is going to call Class_Name::stream_sorter as the comparison function, passing it two arguments. The return value is a function, but usort expects an integer telling it which of the arguments was greater. You need to pass the return value of Class_Name::stream_sorter to usort, not the function itself:

usort($array, self::zstream_sorter());

Upvotes: 7

Related Questions