在PHP中将数组传递给函数而不是单独的值的缺点

时间:2017-06-16 07:38:02

标签: php arrays function

请查看以下两个代码。

代码01

test_function($user_name, $user_email, $user_status, $another)

function test_function($user_name, $user_email, $user_status, $another){
    //Do What You Want
}

代码02

$pass_data = array(
                "user_name"=>$user_name,
                "user_email"=>$user_email,
                "user_status"=>$user_status,
                "another"=>$another,
                );

test_function($pass_data)

function test_function($pass_data){
    //Do What You Want
}

当我使用Code 01时,如果我想添加另一个变量,我想要更改两个标头。有时我觉得当有很多参数时代码也不清楚。

所以我想要使用第二种方式。但我没有看到程序员通常在他们的所有代码中使用第二种方式。

那么使用Code 02的缺点是什么?这意味着,将数组传递给函数而不是单独的值

1 个答案:

答案 0 :(得分:2)

在强类型语言(如C#)中或者如果使用类型提示,则可以允许代码进行类型检查,例如,在情况2中你可以说(如果使用PHP 7 +)。

function test(string $user_name, string $email, int $user, SomeClass $another)

然后解释器在没有获得正确的参数类型时会抛出错误,并且您不必进行手动类型检查或让脚本尽可能地处理它。

您无法在数组成员上键入提示,因此您将失去该功能。

如果你没有输入提示,那么你的工作方式没有区别,事实上你可以通过以下方式轻松地从一个切换到另一个:

$pass_data = array(
  "user_name"=>$user_name,
  "user_email"=>$user_email,
  "user_status"=>$user_status,
  "another"=>$another,
);

test_function_one($pass_data);
test_function_two(...array_values($pass_data)); //or call_user_func_array for older PHP versions

function test_function_one($pass_data){
    extract($pass_data);
    // $user_name, $user_email, $user_status, $another are now set
}

function test_function_two($user_name, $user_email, $user_status, $another){
     $pass_data = func_get_args(); 
}