Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中将数组传递给函数而不是单独的值的缺点_Php_Arrays_Function - Fatal编程技术网

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

PHP中将数组传递给函数而不是单独的值的缺点,php,arrays,function,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,

请看下面两个代码

代码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
}
当我使用代码01时,如果我想添加另一个变量,我想更改两个标题。有时,我觉得当有许多参数时,代码也不清楚

所以我想用第二种方法。但我没有看到程序员在所有代码中都使用第二种方式


那么使用代码02的缺点是什么?这意味着,在强类型语言(如C#)中,将数组传递给函数而不是单独的值,或者如果使用类型暗示,则可以允许代码进行类型检查,例如,在案例2中,您可以说(如果使用PHP7+)

当解释器没有获得正确的参数类型时,解释器将抛出错误,您不必进行手动类型检查,也不必让脚本尽可能地处理它

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

如果您不键入hint,那么如何使用它也没什么区别,事实上,您可以通过以下两种方式轻松地从一种切换到另一种:

$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(); 
}

在向函数传递选项时,我见过类似的代码。此外,还经常将
extract
与它结合使用。
$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(); 
}