5

I've just built myself a function that fetches the URI string and turns it into an array as shown below. This example is based upon the URL of http://mydomain.com/mycontroller/mymethod/var

Array
(
    [0] => mycontroller
    [1] => mymethod
    [2] => var
)

If I write new $myArray[0];, I will load the myController class, but can I make a function that handles the eventual existance of methods and their calling with their respective variables?

2 Answers 2

8

I am not sure what you mean by "handles the eventual existance of methods and their calling with their respective variables", but you might be after call_user_func_array:

call_user_func_array(
    array($myArray[0], $myArray[1]),
    array($myArray[2])
);

If you want to do that for the concrete instance you created with $controller = new $myArray(0), replace $myArray[0] with $controller, e.g.

$controller = new $myArray(0);
call_user_func_array(
    array($controller, $myArray[1]),
    array($myArray[2])
);

or pass new $myArray[0] if you dont care about the instance being lost after the call

call_user_func_array(
    array(new $myArray[0], $myArray[1]),
    array($myArray[2])
);

Otherwise you'll get an E_STRICT notice and cannot reference $this in whatever myMethod is. Also see the PHP manual on possible callback formats.


To validate the method and class actually exist, you can use

Example:

if (method_exists($myArray[0], $myArray[1])) {
    call_user_func_array(*/ … */)
}

Please clarify your question if something else is meant. On a sidenote, this was probably answered before, but since I am not sure what the question is, I am also not sure which of those to pick.

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

2 Comments

this only works with static methods, else you need an instance of the class
@kemp not true, but added clarification. I think that's what you meant.
1

I guess this would also work:

$obj = new $myArray[0];
$obj->{$myArray[1]}($myArray[2]);

Comments

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.