Can I call methods with variables?

eval, php

Solution

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

Problem

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!

Original source