I'm investigating methods of obtaining multiple parameters in the methods or functions PHP, something like:
public function fx($param1, $param2, $param3, ....)
{
// do something...
}
Right now we can make these types of statements in PHP
public function foo($param1, $param2) {} // parameters 1 and 2 are mandatory
public function foo($param1, $param2 = "", $param3 = "") {} //param1 is mandatory, param two and tree are optional but if i can need set $param3 we need set $param2...
Now my question is how can I have multiple parameters and can declare in diferent and that order does not matter in the statement. Something like this:
public function foo($param1, $param2 = "", $param3 = "")
{
echo "Result from $param1 is :" . $param2 / $param3;
}
foo("first", $param2 = 0 , $param3 = 1); // "Result from foo is : 0"
foo("second", $param3 = 1, $param2 = 0); // "Result from bar is : 0"
I can do something like this, getting all arguments and then process with func_get_args
. There is something like what I want , or at least implement a method to achieve?
If you want named parameters that you can set in any order you like, you can use associative arrays to do that:
<?php
function foo($params)
{
$defaults = array(
'param2' => 2,
'param3' => 3
);
$params = array_merge($defaults, $params);
if (!isset($params['param1'])) {
throw new \InvalidArgumentException('Missing param1');
}
echo "Result from $param1 is :" . $params['param2'] / $params['param3'];
}
foo(array(
'param1' => 1,
'param2' => 10,
'param3' => 2
));