0

I wrote a really simple function thinking it would only output its parameter if it exists:

  function hurl($var,$default="")
  {
    if(isset($var) && !is_null($var) && gettype($var) != "object" && gettype($var) != "array")
        return $var;
    return $default;
  }

This way you can simply hurl($_POST['variable']) and it wouldn't generate an error if the POST variable didn't exist. But I still get an error as if it is trying to reference a value that doesn't exist.

Then i read a notice on the isset() documentation:

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

This linked me to Variable Functions which read:

Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

How can I do this? Could someone write an example, or a simpler method of checking without having to constantly write isset() and is_null() all over the page? Would a try catch statement work in this scenario somehow?

1 Answer 1

0

You can do something like this:

function hurl($key, $value='') {
    if (array_key_exists($key, $_POST)) {
        if (!is_object($_POST[$key]) && !is_array($_POST[$key])) {
            $value = $_POST[$key];
        }
    }
    return $value
}
1
  • Thought of this solution too, but didn't know if RecoJohnson wanted a solution for all kind of variables.
    – djot
    Sep 9, 2013 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.