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 by calling the function with eval() like so:
eval('$this->'.$lstrClassName.'->'.$lstrMethodName.'($laParameters);');
I'm curious if there is a beter way to solve this.
Thanks!
You could try something like: Method m = obj. getClass(). getMethod("methodName" + MyVar); m.
You can't. Variables defined inside a method are local to that method. If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Because the variable that you have declared in main method is a local variable and accessible to main method only. For accessing variable between methods declare it as an instance varibale, which is accessible by all class members.
You don't need eval to do that ... depending on your version
Examples
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 having to declare variables
You might also want to look at call_user_func
http://php.net/manual/en/function.call-user-func.php
Did you try your code? The best way to find out if something will work is by trying it. If you do try it, you will find that yes, it does work (assuming that $this
has a property called Class
which is an instance of an object that defines a method called function
).
There are also the two functions call_user_func()
and call_user_func_array()
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