请看下面两段代码。
代码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 时,如果我想添加另一个变量,我想更改两个 header 。有时我感觉参数很多时代码也不清楚。 .
所以我想到使用第二种方式。但我还没有看到程序员在所有代码中普遍使用第二种方式。
那么使用代码 02 有什么缺点?这意味着将数组传递给函数而不是单独的值。
最佳答案
在强类型语言(如 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();
}
关于php - 在 PHP 中将数组传递给函数而不是单独的值的缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44583527/