6

Can i pass the entire POST array into a function and handle it within the function?

such as

PostInfo($_POST);


function PostInfo($_POST){
    $item1 = $_POST[0];
    $item2 = $_POST[1];
    $item3 = $_POST[2];
        //do something
return $result;

}

or is this the correct way of doing this?

mrpatg
  • 10,001
  • 42
  • 110
  • 169
  • 1
    Those are superglobal variable. You may see them in every functions, if register_global is on. – Aif Nov 02 '09 at 12:09
  • 1
    Please note that `register_globals` (not `register_global`) is not required to use `$HTTP_POST_VARS` (the non-superglobal and deprecated brother to `$_POST`)! See here: http://de.php.net/manual/en/ini.core.php#ini.register-globals – Stefan Gehrig Nov 02 '09 at 12:21
  • Right, that was my other guess as to it's use. Couldn't remember exactly, but I knew Aif was wrong. At any rate, `register_globals` is **bad**! Beyond that, it's deprecated. Don't use it! – Matthew Scharley Nov 02 '09 at 12:33
  • 1
    Related: [PHP: $_GET and $_POST in functions?](http://stackoverflow.com/q/1354691/367456) – hakre Jul 09 '13 at 07:25

3 Answers3

9

Yes. If you are going to name the local variable $_POST though, don't bother. $_POST is a 'superglobal', a global that doesn't require the global keyword to use it outside normal scope. Your above function would work without the parameter on it.

NOTE You cannot use any superglobal (i.e. $_POST) as a function argument in PHP 5.4 or later. It will generate a Fatal error

Machavity
  • 30,841
  • 27
  • 92
  • 100
Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
9

You can actually pass $_POST to any function which takes in an array.

function process(array $request)
{

}

process($_POST);
process($_GET);

Great for testing.

Jimbo
  • 25,790
  • 15
  • 86
  • 131
Extrakun
  • 19,057
  • 21
  • 82
  • 129
  • 2
    This is the preferred way to do it. It's called [dependency injection](http://stackoverflow.com/questions/130794/what-is-dependency-injection) – Machavity Apr 17 '15 at 14:21
2

The $_POST-array is an array like every other array in PHP (besides being a so-called superglobal), so you can pass it as a function parameter, pass it around and even change it (even though this might not be wise in most situations).

Regarding your code, I'd change it a bit to make it more clear:

PostInfo($_POST);

function PostInfo($postVars)
{
    $item1 = $postVars[0];
    $item2 = $postVars[1];
    $item3 = $postVars[2];
        //do something
    return $result;
}

This will visibly separate the function argument from the $_POST superglobal. Another option would be to simple remove the function argument and rely on the superglobal-abilities of $_POST:

PostInfo();

function PostInfo()
{
    $item1 = $_POST[0];
    $item2 = $_POST[1];
    $item3 = $_POST[2];
        //do something
    return $result;
}
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189