Can I call methods with variables?
Can I do the following in PHP?
$lstrClassName = 'Class';
$lstrMethodName = 'function';
$laParameters = array('foo' => 1, 'bar' => 2);
$this->$lstrClassName->$lstrMethodName($laParameters);
The solution I'm using now is to call the function with eval () like this:
eval('$this->'.$lstrClassName.'->'.$lstrMethodName.'($laParameters);');
I'm curious if there is a way to solve this problem.
Thank!
source to share
You don't need eval for this ... depending on your version
Examples of
class Test {
function hello() {
echo "Hello ";
}
function world() {
return new Foo ();
}
}
class Foo {
function world() {
echo " world" ;
return new Bar() ;
}
function baba() {
}
}
class Bar {
function world($name) {
echo $name;
}
}
$class = "Test";
$hello = "hello";
$world = "world";
$object = new $class ();
$object->$hello ();
$object->$world ()->$world ();
$object->$world ()->$world ()->$world(" baba ");
Output
Hello World baba
And if you are using PHP 5.4 you can just call it directly without declaring variables
You can also look at call_user_func
http://php.net/manual/en/function.call-user-func.php
source to share
Have you tried your code? The best way to find out if something will work is to try it. If you try this, you find that yes, it works (assuming it $this
has a property Class
that is an instance of an object that defines a named method function
).
There are also two functions call_user_func()
andcall_user_func_array()
source to share
I would suggest you call_user_func_array , which can be used for functions and for arrays, not eval. However, the syntax is different from what you suggested and the fact that I try to avoid eval whenever possible, you can use it with:
To call it using objects, just do it like this:
$return=call_user_func_array(array($objInstance, "CLASSMETHOD"), $paramArray);
source to share