0

In App.php file I have this:

For URL like this one: 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.

In my controller file I have:

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]);

    }

So my question is, why in my controller I dont have that $params as array, but just first element of array. If I instead do:

    public function index($param1, $param2){

I will have all of them, but I want flexibility in terms of how many of params I will get.

1 Answer 1

2

You want to use call_user_func not call_user_func_array

call_user_func takes first parameter as callable and rest send as parameters to the function. While call_user_func_array expects exactly two parameters - first one is callable the second one is an array with parameters of the called function. See following example:

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'));

first (call_user_func) will dump:

array(2) { [0]=> string(3) "one" [1]=> string(3) "two" }
NULL

while the call_user_func_array will result in:

string(3) "one"
string(3) "two" 

Hope it helps

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I managed to do with first one also, using func_get_args(), but still like your solution better, as it's cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.