Should My PHP Functions Accept an Array of Arguments or Should I Explicitly Request Arguments

Should my PHP functions accept an array of arguments or should I explicitly request arguments?

If the system is changing so often that using an indexed array is the best solution, I'd say this is the least of your worries. :-)

In general functions/methods shouldn't take too many arguments (5 plus or minus 2 being the maximum) and I'd say that you should stick to using named (and ideally type hinted) arguments. (An indexed array of arguments only really makes sense if there's a large quantity of optional data - a good example being configuration information.)

As @Pekka says, passing an array of arguments is also liable to be a pain to document and therefore for other people/yourself in 'n' months to maintain.

Update-ette...

Incidentally, the oft mentioned book Code Complete examines such issues in quite a bit of detail - it's a great tome which I'd highly recommend.

Passing array of parameters vs. individual parameters to a function in PHP?

Theoretically, each parameter should encompass a logical whole. Collections are meant to represent a collection of values, not an aggregate of method parameters; the individual parameters should be passed separately to clearly indicate the purpose of the method.

Practically, when passing parameters in an array, you have to do a ton of manual checks to ensure that correct parameters have been passed. You can avoid pretty much any ambiguity by giving your parameters clear, logical names (and typehints where possible). Also, as a comment already stated, if a method takes 7 parameters, it's probably ripe for some refactoring.

Edit: if your method/function does accept a set of vaguely defined "options" that affect what the code does only in a minor way, consider using the Symfony OptionsResolver component, to greatly ease the validation of your options array.

Php function use only specified arguments

In such cases, you can specify default arguments. If the arguments aren't specified during the function call, then their default value will be used.

function MyFunction($conditionArg, $arg1=null, $arg2=null, $arg3=null, $arg4=null) {
if($conditionArg == "something") {
// use arguments 1 and 2
}
elseif($conditionArg == "something else") {
// use arguments 3 and 4
}
}

Now, all the following function calls will work fine:

MyFunction("something");
MyFunction("something", $arg1);
MyFunction("something", $arg1, $arg2);
MyFunction("something", $arg1, $arg2, $arg3);
MyFunction("something", $arg1, $arg2, $arg3, $arg4);

See also: Should my PHP functions accept an array of arguments or should I explicitly request arguments?

Emulating named function parameters in PHP, good or bad idea?

I would suggest using the associative array to pass named parameters, but keep them in the array without extracting them.

function myFunc(array $args) {
echo "Hi, " . $args['name'];
// etc
}

There's a couple of reasons for this. Looking at that function, you can quite clearly see that I'm referring to one of the arguments passed into the function. If you extract them, and don't notice the extract() you (or the next guy) will be there scratching your head wondering where this "$name" variable came from. Even if you do know you're extracting the arguments to local variables, it's still a guessing game to a certain degree.

Secondly, it ensures that other code doesn't overwrite the args. You may have written your function expecting only to have arguments named $foo and $bar, so in your other code, you define $baz = 8;, for example. Later on, you might want to expand your function to take a new parameter called "baz" but forget to change your other variables, so no matter what gets passed in the arguments, $baz will always be set to 8.

There are some benefits to using the array too (these apply equally to the methods of extracting or leaving in the array): you can set up a variable at the top of each function called $defaults:

function myFunc (array $args) {
$default = array(
"name" => "John Doe",
"age" => "30"
);
// overwrite all the defaults with the arguments
$args = array_merge($defaults, $args);
// you *could* extract($args) here if you want

echo "Name: " . $args['name'] . ", Age: " . $args['age'];
}

myFunc(array("age" => 25)); // "Name: John Doe, Age: 25"

You could even remove all items from $args which don't have a corresponding $default value. This way you know exactly which variables you have.

can php function parameters be passed in different order as defined in declaration

Absolutely not.

One way you'd be able to pass in unordered arguments is to take in an associative array:

function F($params) {
if(!is_array($params)) return false;
//do something with $params['A'], etc...
}

You could then invoke it like this:

F(array('C' => 3, 'A' => 1, 'B' => 1));

PHP Function with Optional Parameters

Make the function take one parameter: an array. Pass in the actual parameters as values in the array.


Edit: the link in Pekka's comment just about sums it up.

Does this function have too many parameters?

You could either pass an array with all variables packed nicely together, or just make a "User" class and add all properties via setters and do the validation in the end with a dedicated method:

class User {

public function setName($name) {
$this->name = $name;
}

[...]

public function register() {

//Validate input
if (empty($this->name))
$this->errors[] = "ERROR, Username must not be emtpy";

//Add the user to the database
//Your SQL query
return empty($this->errors);
}

}

$user = new User();
$user->setName("Peter");
$success = $user->register();

if (!$success)
echo "ERRORS OCCURED: ".print_r($user->errors, true);

Using an array of vars name to call a function

You can pass it as array to the function and do a foreach inside the function.

Your variables:

$variables = array($var1, $var2, $var3, $varN);

The function:

function addToTable($array = [])
{
foreach ($array as $key => $value) {
// Do stuff here
}
}

And you call the function like this:

addToTable($variables);


Related Topics



Leave a reply



Submit