passing POST array to php function

前端 未结 3 583
忘掉有多难
忘掉有多难 2020-12-20 23:46

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

such as

PostInfo($_POST);


function PostInfo($_POST){
    $item1         


        
相关标签:
3条回答
  • 2020-12-21 00:32

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

    function process(array $request)
    {
    
    }
    
    process($_POST);
    process($_GET);
    

    Great for testing.

    0 讨论(0)
  • 2020-12-21 00:33

    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;
    }
    
    0 讨论(0)
  • 2020-12-21 00:45

    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

    0 讨论(0)
提交回复
热议问题