PHP: calling a class from an array?

I just created a function that fetches a URI string and turns it into an array, as shown below. This example is based on the urlhttp://mydomain.com/mycontroller/mymethod/var

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

If I write new $myArray[0];, I will load the class myController, but can I create a function that handles the possible existence of methods and their call with their corresponding variables?

+5
source share
2 answers

I'm not sure what you mean by “handles the possible existence of methods and their invocation with their corresponding variables,” but you can after call_user_func_array:

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

, $controller = new $myArray(0), $myArray[0] $controller, .

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

new $myArray[0], , ,

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

E_STRICT $this myMethod. . PHP .


,

:

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

, . , , , , , , .

+8

, :

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

All Articles