What if call_user_func should return false?

The function that I call with call_user_funcshould return FALSE. So, how can I detect errors if the called is invalid?

(Lateral note: why didn’t they have this exception and not return an error code? Or is there a way to "catch" the error? I have an error descriptor. Should I have exceptions for me?)

+5
source share
2 answers

If you want to check if a function or method really exists, you can use is_callableit before calling call_user_func. You can wrap all this with a function for easy reuse:

function call_uf($fn) {
    if(is_callable($fn)) {
        return call_user_func($fn);
    } else {
        throw new Exception("$fn is not callable");
    }
}

, PHP . , , PHP5, PHP . , , :

PHP , . ErrorException.

+10

, . PHP , PHP < 5.

"" . , , . , , , - .

, , :

function safe_call_user_func()
{
  $nargs = func_num_args();
  $args = func_get_args();
  if ( $nargs == 0 )
    throw new RuntimeException( 'Require at least the callback param' );
  if ( !is_callable( $args[0] )
    throw new InvalidArgumentException( 'Callback param is invalid' );
  return call_user_func_array( array_shift( $args ), $args );
}
+1

All Articles