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?
When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).
The call_user_func() is an inbuilt function in PHP which is used to call the callback given by the first parameter and passes the remaining parameters as argument. It is used to call the user-defined functions.
<? php class myClass{ function doSomething($str){ //Something is done here } function doAnother($str){ return doSomething($str); } } ?>
PHP | get_class_methods() Function The get_class_methods() function is an inbuilt function in PHP which is used to get the class method names. Parameters: This function accepts a single parameter $class_name which holds the class name or an object instance.
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
method_exists
— Checks if the class method existsExample:
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.
I guess this would also work:
$obj = new $myArray[0];
$obj->{$myArray[1]}($myArray[2]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With