Industrial
Industrial

Reputation: 42788

PHP: Call a class from array?

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?

Upvotes: 5

Views: 300

Answers (2)

Gordon
Gordon

Reputation: 317039

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.

Upvotes: 8

rsenna
rsenna

Reputation: 11963

I guess this would also work:

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

Upvotes: 1

Related Questions