我有一个类,其属性和方法类似于下面显示的代码,只是更复杂。我们的想法是在调度数组中调用一个元素,然后为该元素列出的方法将按列出的顺序执行。我坚持如何获取执行方法(请参阅名为execute()的方法)。这甚至可能吗?
请注意,在构造函数中调用了setDispatch(),该代码未在下面的代码中显示。
// attribute
private $_dispatch = [];
// methods
public function execute()
{
$dispatch = $this->getDispatch();
// NEED LOGIC HERE THAT EXECUTES METHODS LISTED IN $dispatch['A']
}
private function setDispatch()
{
$this->_dispatch = [
'A' => [
'method1',
'method2',
'method3'
],
'B' => [
'method4',
'method3',
'method1'
]
];
}
private function getDispatch()
{
return $this->_dispatch;
}
private function method1()
{
//do something
}
private function method2()
{
//do something
}
private function method3()
{
//do something
}
private function method4()
{
//do something
}

答案 0 :(得分:6)
我相信你会喜欢call_user_func和php call class function by string name
请记住,call_user_func将不会像你的情况那样工作,你需要使用callback syntax,这意味着方法名称应该在数组中,并带有对象的链接:[$object, $methodName]
// attribute
private $_dispatch = [];
// methods
public function execute()
{
$dispatch = $this->getDispatch();
foreach($dispatch['A'] as $methodName){
call_user_func([$this, $methodName]);
}
}
private function setDispatch()
{
$this->_dispatch = [
'A' => [
'method1',
'method2',
'method3'
],
'B' => [
'method4',
'method3',
'method1'
]
];
}
private function getDispatch()
{
return $this->_dispatch;
}
private function method1()
{
//do something
}
private function method2()
{
//do something
}
private function method3()
{
//do something
}
private function method4()
{
//do something
}