在App.php
档案中我有这个:
对于像这样的网址:http://mywebroot/myapp/param1/param2
# anything leftover in $url, set as params, else empty.
$this->params = $url ? array_values($url) : [];
print_r($this->params); // this gives me dumped array values as it should
// so I can see Array ( [0] => param1 [1] => param2 )
// Now I am trying to pass that array to my controller:
//
//
# call our method from requested controller, passing params if any to method
call_user_func_array([
$this->controller,
$this->method
], $this->params); // Don't worry about `$this->controller`,
// `$this->method` part, it will end up calling method from the class bellow.
在我的控制器文件中,我有:
class Home extends Controller {
// here I am expecting to catch those params
//
public function index($params = []){
var_dump($params); // This gives `string 'param1' (length=6)`? WHERE IS ARRAY?
// not relevant for this question
# request view, providing directory path, and sending along some vars
$this->view('home/index', ['name' => $user->name]);
}
所以我的问题是,为什么在我的控制器中我没有$params
作为数组,而只是数组的第一个元素。
如果我改为:
public function index($param1, $param2){
我将拥有所有这些,但我希望灵活性方面我会得到多少参数。
答案 0 :(得分:2)
您想使用call_user_func
而不是call_user_func_array
call_user_func
将第一个参数作为callable
,其余作为参数发送给函数。虽然call_user_func_array
只需要两个参数 - 第一个是callable
,第二个是带有被调用函数参数的数组。请参阅以下示例:
function my_func($one, $two = null) {
var_dump($one);
var_dump($two);
}
call_user_func('my_func', array('one', 'two'));
call_user_func_array('my_func', array('one', 'two'));
首先(call_user_func
)将转储:
array(2) { [0]=> string(3) "one" [1]=> string(3) "two" }
NULL
而call_user_func_array
将导致:
string(3) "one"
string(3) "two"
希望有所帮助