4

I am trying to mimic php's inbuilt usort function definition in my implementation below:

class heapSort {
    static function hsort(array &$array, callable $cmp_function){
       // logic
    }
}

class utility{
    static function mycomparator(){
        // logic
    }
}

$array = array(5,3,8,1);
$callback = array('utility','mycomparator');
heapSort::hsort($array, $callback);

While the variable $callback is "callable" why do I get below fatal error?

Argument 2 passed to heapSort::hsort() must be an instance of callable.

More specifically, how do I make/typecast a $variable to callable?

Sammitch
  • 30,782
  • 7
  • 50
  • 77
pranay
  • 444
  • 1
  • 7
  • 20
  • 2
    `callable` isn't an actual type until 5.4, see [the docs](http://php.net/manual/en/language.types.callable.php) for more info, but your code seems to be correct. What version of PHP is this? – Sammitch Apr 04 '13 at 18:00
  • because your callback is not a valid one , try "utility::mycomparator" .instead of an array. – mpm Apr 04 '13 at 18:03

1 Answers1

5

callable is only supported PHP 5.4 try using is_callable instead

static function hsort(array &$array, $cmp_function) {
    if (! is_callable($cmp_function))
        throw new InvalidArgumentException("Function not callable");
}
Baba
  • 94,024
  • 28
  • 166
  • 217
  • After my own testing I was about to post this same code. If you change the original code from `callable $cmp_function` to `potato $cmp_function` you will get the error: `Argument 2 passed to heapSort::hsort() must be an instance of potato`. – Sammitch Apr 04 '13 at 18:07
  • The OP wants callable .. you got the error because `potato` did not implement `__invoke` see http://www.php.net/manual/en/language.oop5.magic.php#object.invoke – Baba Apr 04 '13 at 18:11
  • 2
    the point of the potato example is to illustrate that the problem is not that the argument was not of the correct type, but that the type OP is declaring does not exist in his version and the error will simply reference any fake type you put in. – Sammitch Apr 04 '13 at 18:41