PHP使用字符串作为方法名调用方法


PHP invoke method using string for method name

我想在我的php类中有一个方法数组,用方法名索引,这样我就可以做这样的事情:

public function executeMethod($methodName){
 $method=$this->methodArray[$methodName];
 $this->$method();
 // or some other way to call a method whose name is stored in variable $methodName
}

我发现__call:

在与属性交互时调用重载方法类中未声明或不可见的方法电流范围

但是,我想在executeMethod中使用的方法是可见的。

正确的方法是什么?这可能吗?

编辑:我想在executeMethod中获得一个方法名称,然后调用给定名称的方法,并且有了方法数组的想法。

您可以通过使用带有语法的字符串调用对象方法和属性

$method = 'your_method_name_as_string';
$this->$method();

from PHP doc

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }
    function Bar()
    {
        echo "This is Bar";
    }
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()
?>

也许你正在寻找这样的东西:

public function executeMethod($methodName) {
    if (isset($this->methodArray[$methodName])) {
        $method = $this->methodArray[$methodName];
        return call_user_func(array($this, $method));
    }
    throw new Exception("There is no such method!");
}

匿名函数在PHP 5.3中可用

我觉得你是想做一些像

$tmp['doo'] = function() { echo "DOO"; };
$tmp['foo'] = function() { echo "FOO"; };
$tmp['goo'] = function() { echo "GOO"; };
$tmp['doo']();