2014-09-10 38 views
0

App.php文件我有这样的:call_user_func_array传递附加PARAMS到方法

对于URL像这样的: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){ 

我将所有的人,但我想在我将如何则params的许多方面获得灵活性。

回答

1

你想用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" 

希望它可以帮助

+0

谢谢,我设法也可以使用'func_get_args()'来处理第一个问题,但仍然更像你的解决方案清洁器。 – branquito 2014-09-10 15:32:02