tags:

views:

169

answers:

4

Have a series of functions I am calling dynamically sort of like this:

$function = 'someFunction';
$x = $function();

.. however, if the function expects parameters, and I don't code it in the call, I seem to crash the page. For example:

function someFunction( $in_param1 ) {
  return "SUCCESS";
}

$function = 'someFunction';
// this next line does not work
$x = $function() or die("error");

How can I handle this kind of error?

Thanks -

+5  A: 

You can catch this using the set_error_handler function:

function handle_errors( $errno, $errstr )
{
    die( "Your error will be caught here" );
}

set_error_handler( "handle_errors" );

$function = 'someFunction';
$x = $function();
Don Neufeld
This is a good answer. I don't know why I didn't think of an error handler as a way to essentially "catch" errors.
Peter Bailey
very nice solution - thanks!
OneNerd
+2  A: 

You could redefine your function with default values for the arguments required like

function someFunction( $in_param1=null ) {
  return "SUCCESS";
}
protobuf
+3  A: 

Suppress? Yes. Catch? See don.neufeld's answer.

$x = @$function();

According to this page, you can enable a specific INI setting so that you can read errors suppressed in this manner.

Peter Bailey
+1  A: 

I don't know about suppressing, but you can get more information about the functions with the ReflectFunction class.

<?php
function foo($a, $b, $c) {}

$func = new ReflectionFunction('foo');
echo $func->getNumberOfParameters();

This outputs "3".

Henrik Paul