Reputation: 317
I need to make a universal caller for addons to my php project. I need to call models based on form field (POST):
$moduleName = new ReflectionClass($module);
$data = $moduleName->method($params);
print_r($data);
This also doesn't work:
$data = call_user_func_array($moduleName.'::method',array($params));
print_r($data);
Why?
Is this right? I get ReflectionClass:method() 'not found or invalid function name' error.
How to call a new instance of the class by name from variable and function name also as variable?
Upvotes: 0
Views: 205
Reputation: 16719
I think you mean:
$className = 'YourClassName';
$methodName = 'classMethodName';
$module = new $className(); // create new class instance
$data = $module->{$methodName}($params); // call your method
if $params
is an array, and you want to pass it to your method as multiple arguments:
$data = call_user_func_array(array($module, $methodName), $params);
Since you tagged this reflection, here's the other way:
$module = new $className();
$reflector = new ReflectionMethod($module, $methodName);
$reflector->invokeArgs($module, $params); // call_user_func_array() equivalent
Obviously you don't need to instantiate your class if the method you're trying to call is static.
Upvotes: 1