PHP call_user_func_array() explanation


I am relatively new to PHP and am working through an MVC framework tutorial. Rather than just copying the code I always try to comment the code as I work through it so I know what each line of code is doing - this helps me to learn and also helps when I refer back to the code at a later date.

I have managed to work out what everything is doing so far (I think!!) but am stuck when I get to a piece of code using the call_user_function_array() function.

If someone could take a look and explain what is going on I would much appreciate it - I have checked the PHP documentation and looked up the function in a book on OO PHP but I am afraid neither is making sense to me!

I have highlighted the code I am struggling to understand:

function callHook(&$url) {
$urlArray = explode("/",$url); # Explodes the string vlaue of $url into array elements using ‘/’ as a delimiter

$controller = array_shift($urlArray); # Removes the first element from $urlArray and assigns it to $controller
$action = array_shift($urlArray); # Removes the new first element from $urlArray and assigns it to $action
$queryString = $urlArray; # Assigns whatever is left in the $urlArray array to $queryString

$controllerName = $controller; # Assign the value of $controller to $controllerName
$controller = ucwords($controller); # Make sure that the first letter of each word in the $controller string is uppercase
$model = rtrim($controller, 's'); # Take the last 's' of the $controller string
$controller .= 'Controller'; # Concat 'Controller' onto the end of the $controller string
$dispatch = new $controller($model,$controllerName,$action); # Create a new object of the class $controller and pass it the current $model,$controllerName,$action values

 if ((int)method_exists($controller, $action)) { # Checks if the current $action method exists in the current $controller class
    call_user_func_array(array($dispatch,$action),$queryString); # If it does exist ???
} else {
        /* TODO Error Generation Code Here */


If I have made any errors in understanding the rest of the code I would also appreciate being corrected.

Many thanks

My understanding after looking through the doc’s is that the function simply calls a user created function.

Thank you.

So in this instance the function being called would be $dispatch->$action and this function would get passed $queryString as an indexed array?

Is that correct?


Have you ran it/ played with to test it out?

Not yet as I didn’t understand what was being called properly. I am going to write some test code for the function now and see if I have the correct understanding.

Thank you for your help and time.

Sponsor our Newsletter | Privacy Policy | Terms of Service