PHP suppress errors in function parameters

368 views Asked by At

Extension from https://stackoverflow.com/a/55191/547210
I am creating a validating function to check several attributes of string variables, which may or may not have been set. (One of the attributes which is checked)
What I am trying to do with the function is receive arguments an unknown number of arguments in the form (See below), and suppress errors that may be caused by passing an unset variable.
I'm receiving the variables like validate([ mixed $... ] ) by using func_get_args()
The previous post mentioned that it was possible by passing by reference, now is this possible when the variables are passed implicitly like this?

1

There are 1 answers

5
DaveRandom On BEST ANSWER

If you pass a variable that is not set in the calling scope, the array returned by func_get_args() will contain a NULL value at the position where the variable was passed, and an error will be triggered. This error is not triggered in the function code itself, but in the function call. There is, therefore, nothing that can be done to suppress this error from within the code of the function.

Consider this:

function accepts_some_args () {
  $args = func_get_args();
  var_dump($args);
}

$myVar = 'value';
accepts_some_args($notSet, $myVar);

/*
  Ouput:

  Notice: Undefined variable: notSet in...
  array(2) {
    [0]=>
    NULL
    [1]=>
    string(5) "value"
  }
*/

As you can see, the variable name notSet appears in the error, telling us that the error was triggered in the caller's scope, not that of the callee.

If we want to counter the error, we could do this:

accepts_some_args(@$notSet, $myVar);

...and prefix the variable names with the evil @ operator, but a better solution would be to structure our code differently, so we can do the checks ourselves:

function accepts_some_args ($args) {
  var_dump($args);
}

$myVar = 'value';

$toPassToFunction = array();
$toPassToFunction[] = (isset($notSet)) ? $notSet : NULL;
$toPassToFunction[] = (isset($myVar)) ? $myVar : NULL;

accepts_some_args($toPassToFunction);

/*
  Ouput:

  array(2) {
    [0]=>
    NULL
    [1]=>
    string(5) "value"
  }
*/