Reputation: 43
I need to define a function in PHP that contains multiple arguments (as shown below):
function the_function($arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $arg7, ...)
but I believe there is a more efficient and clean method of doing this. Can anyone help me? I thought of using an array, something like that. obs: sorry for the noob question! :b
Edit: i'll use something like
function foo(
'number of topics', 'topics per page', 'topics per line'
, 'type of topic', 'number of excerpt words'
);
Upvotes: 2
Views: 55
Reputation: 173552
I think you can go three ways with this:
If all arguments are semantically the same, use func_get_args()
within your function to iterate over the given arguments. A single array argument is a respected alternative.
If most arguments are semantically the same, group them together as a single array argument. Treat the other arguments separately.
In all other cases, group related arguments together into a separate object.
They're not entirely mutually exclusive btw.
Upvotes: 2
Reputation: 43745
An array is the standard approach to avoiding a ton of arguments (if a function does truly need that many). Just consider whether or not the type of things in the array are numerical in nature or if naming them makes sense. You may want to pass in an associate array rather than numerical. Of course, be absolutely sure that the function really needs those arguments and can't be broken down further.
Here's just a random example where an associative array might make sense.
$phone = [
'home' => '555-5551',
'cell' => '555-5552',
'work' => '555-5553'
];
function updateUserInfo($userId, $age, array $phone) {
}
rather than:
function updateUserInfo($userId, $age, $homePhone, $cellPhone, $workPhone) {
}
Upvotes: 1
Reputation: 41428
I recommend sticking to declaring your arguments explicitly. It makes for easier testing and less ambiguity. Also, you can enforce some type checking on objects and arrays.
function foo( User $user, array $user_friend_ids);
Upvotes: 0