我正在研究在方法或函数PHP中获取多个参数的方法,例如:
public function fx($param1, $param2, $param3, ....)
{
// do something...
}
现在我们可以在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...
现在我的问题是如何才能拥有多个参数并且能够以不同的方式声明,并且该语句中的顺序无关紧要。像这样:
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"
我可以做这样的事情,获取所有参数然后用func_get_args
处理。有类似我想要的东西,或者至少实现一种方法来实现?
答案 0 :(得分:4)
如果您想要以您喜欢的任何顺序设置的命名参数,可以使用关联数组来执行此操作:
<?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
));