Call method by string?
Try:
$this->{$this->data['action']}();
Be sure to check if the action is allowed and it is callable
<?php
$action = 'myAction';
// Always use an allow-list approach to check for validity
$allowedActions = [
'myAction',
'otherAction',
];
if (!in_array($action, $allowedActions, true)) {
throw new Exception('Action is not allowed');
}
if (!is_callable([$this, $action])) {
// Throw an exception or call some other action, e.g. $this->default()
throw new Exception('Action is not callable');
}
// At this point we know it's an allowed action, and it is callable
$this->$action();
Calling a method named string at runtime in Java and C
In java it can be done through the reflection api.
Have a look at Class.getMethod(String methodName, Class... parameterTypes)
.
A complete example (of a non-static method with an argument) would be:
import java.lang.reflect.*;
public class Test {
public String methodName(int i) {
return "Hello World: " + i;
}
public static void main(String... args) throws Exception {
Test t = new Test();
Method m = Test.class.getMethod("methodName", int.class);
String returnVal = (String) m.invoke(t, 5);
System.out.println(returnVal);
}
}
Which outputs:
Hello World: 5
Call methods by string
func_list= ["function1", "function2", "function3"]
class doit(object):
def __init__(self):
for item in func_list:
getattr(self, item)()
def function1(self):
print "f1"
def function2(self):
print "f2"
def function3(self):
print "f3"
>>> doit()
f1
f2
f3
For also private functions:
for item in func_list:
if item.startswith('__'):
getattr(self, '_' + self.__class__.__name__+ item)()
else:
getattr(self, item)()
.
getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
http://docs.python.org/library/functions.html#getattr
How to execute a JavaScript function when I have its name as a string
Don't use eval
unless you absolutely, positively have no other choice.
As has been mentioned, using something like this would be the best way to do it:
window["functionName"](arguments);
That, however, will not work with a namespace'd function:
window["My.Namespace.functionName"](arguments); // fail
This is how you would do that:
window["My"]["Namespace"]["functionName"](arguments); // succeeds
In order to make that easier and provide some flexibility, here is a convenience function:
function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}
You would call it like so:
executeFunctionByName("My.Namespace.functionName", window, arguments);
Note, you can pass in whatever context you want, so this would do the same as above:
executeFunctionByName("Namespace.functionName", My, arguments);
How to call a function from a string stored in a variable?
$functionName()
or call_user_func($functionName)
Call Method based on String
You'll have to use reflection:
Method m = Main.class.getMethod("doBlah");
m.invoke(new Main(), null)
You can add many more other arguments both for retrieving the method and invoking it, all of which can be found here.
How do I call instance method from string?
I have adapted the example given in the update:
class Foo
def method1
puts "i'm method1"
end
def method2
puts "i'm method2"
end
def method3
puts "i'm method3"
end
def bar
{ "ctrl": -> { method1 },
"shift": -> { method2 },
"alt": -> { method3 }
}
end
def [](method)
bar[method]
end
end
binding = ["ctrl", "shift", "alt"].sample
foo = Foo.new
foo[binding].call #=> one of them
Working Example
Calling a function of a module by using its name (a string)
Given a module foo
with method bar
:
import foo
bar = getattr(foo, 'bar')
result = bar()
getattr
can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
Related Topics
Prevent Session Expired in PHP Session for Inactive User
Bulk Rename Files in a Folder - PHP
How to Reset MySQL Pointer Back to the First Row in PHP
Extending Sonata User Bundle and Adding New Fields
Set Character Set Using MySQLi
PHP Pdo. Error Number '00000' When Query Is Correct
Get Only Filename from Url in PHP Without Any Variable Values Which Exist in the Url
How to Install Gd on My Windows Server Version of PHP
Array Combine Three or More Arrays with PHP
How to Check for Special Characters PHP
HTML Form PHP Post to Self to Validate or Submit to New Page
Subtracting a Certain Number of Hours, Days, Months or Years from Date
How to Send an Email Using PHP at Windows Azure