2

Please look at the following two codes.

Code 01

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

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

Code 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
}

When I am using Code 01, if I want to add another variable I want to change both headers. sometimes I feel like code also unclear when there are many parameters. .

So I thought to use the second way. But I have not seen that programmers generally use the second way in all their codes.

So what are the disadvantages using Code 02? That means, passing array to function instead of separate values.

1
  • I have seen similar code, when passing options to a function. Also often extract php.net/manual/de/function.extract.php is being used in conjunction with it. Commented Jun 16, 2017 at 7:42

1 Answer 1

2

In strongly typed languages (like C#) or if you use type hinting, then you can allow the code to do type checking, e.g., in case 2 you can say (if using PHP 7+).

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

The interpreter will then throw errors when it does not get the correct parameter types and you don't have to do manual type checks or let the script deal with it as best as it can.

You can't type-hint on array members so you're losing that functionality.

If you don't type hint then it makes no difference how you'll work it, in fact you can easily switch from one to the other either by:

$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(); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.