我想在我的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中获取一个方法名,然后调用给定名称的方法,并了解方法数组。
答案 0 :(得分:1)
您可以使用带语法的字符串
来调用对象方法和属性$method = 'your_method_name_as_string';
$this->$method();
来自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()
?>
答案 1 :(得分:0)
也许你正在寻找这样的东西:
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!");
}
答案 2 :(得分:0)
anonymous functions在php 5.3中可用
我认为你正在尝试做类似
的事情$tmp['doo'] = function() { echo "DOO"; };
$tmp['foo'] = function() { echo "FOO"; };
$tmp['goo'] = function() { echo "GOO"; };
$tmp['doo']();