简体   繁体   English

将POST数组传递给php函数

[英]passing POST array to php function

Can i pass the entire POST array into a function and handle it within the function? 我可以将整个POST数组传递给函数并在函数内处理它吗?

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? 或者这是正确的方法吗?

Yes. 是。 If you are going to name the local variable $_POST though, don't bother. 如果您要命名本地变量$_POST ,请不要打扰。 $_POST is a 'superglobal', a global that doesn't require the global keyword to use it outside normal scope. $_POST是一个'超全局',一个不需要global关键字在正常范围之外使用它的global Your above function would work without the parameter on it. 您的上述功能可以在没有参数的情况下工作。

NOTE You cannot use any superglobal (ie $_POST ) as a function argument in PHP 5.4 or later. 注意在PHP 5.4或更高版本中,不能使用任何超全局(即$_POST )作为函数参数。 It will generate a Fatal error 它会产生致命错误

You can actually pass $_POST to any function which takes in an array. 您实际上可以将$ _POST传递给任何接收数组的函数。

function process(array $request)
{

}

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

Great for testing. 非常适合测试。

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). $_POST -array是一个像PHP中的每个其他数组一样的数组(除了是一个所谓的超全局 ),所以你可以将它作为函数参数传递,传递它甚至改变它(尽管这可能不是明智的大多数情况)。

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. 这将明显地将函数参数与$_POST超全局分开。 Another option would be to simple remove the function argument and rely on the superglobal-abilities of $_POST : 另一种选择是简单地删除函数参数并依赖$_POST的超全局能力:

PostInfo();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM