Can I call methods with variables?

2019-06-23 23:26发布

问题:

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!

回答1:

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



回答2:

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()



回答3:

I would suggest you call_user_func_array which can be used for functions and for arrays rather than eval. However the syntax is different from what you suggested, and the fact that I tend to avoid eval while possible, you can use it with:

To call it with objects, just do it like:

$return=call_user_func_array(array($objInstance, "CLASSMETHOD"), $paramArray);



回答4:

Untested but

this->$$lstrClassName->$$lstrMethodName($laParameters); 

http://php.net/manual/en/language.variables.variable.php



标签: php eval