我正在尝试建立一个处理所提供数据的系统,并使用addHandler()调用分配给它们的函数。
代码:
class Test {
public $arrHandlers = array();
public function addHandler($action, $function) {
$this->arrHandlers[$action] = $function;
}
public function handleData($data) {
$data = explode("/", $data);
$action = array_shift($data);
if(isset($this->arrHandlers[$action])) {
call_user_func_array($this->arrhandlers[$action], array($data));
}
}
}
function testFunc() {
echo implode(" ", func_get_args());
}
$obj = new Test();
$data = "egg/I/like/cheese";
$obj->addHandler("egg", "testFunc");
$obj->handleData($data);
输出的内容:
Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given on line 13
我想要输出的内容:
I like cheese
答案 0 :(得分:2)
工作代码:
class Test {
public $arrHandlers = array();
public function addHandler($action, $function) {
$this->arrHandlers[$action] = $function;
}
public function handleData($data) {
$data = explode("/", $data);
$action = array_shift($data);
if(isset($this->arrHandlers[$action])) {
call_user_func_array($this->arrHandlers[$action], $data);
}
}
}
function testFunc() {
echo implode(" ", func_get_args());
}
$obj = new Test();
$data = "egg/I/like/cheese";
$obj->addHandler("egg", "testFunc");
$obj->handleData($data);
我将'arrhandlers
'代替'arrHandlers
'并将$ data作为'array($data)
'而不仅仅是'$data
'传递给call_user_func_array()
。