2014-02-17 36 views
1

我想使一個系統處理提供的數據,並調用addHandler()數組中分配給它們的函數。Call_user_func_array()期望參數1是一個有效的回調(事件處理程序系統)

代碼:

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 
+2

'$ this-> arrHandlers!= $ this-> arrhandlers'。你有'E_NOTICE'顯示在你的'error_reporting'中嗎?你應該在關於'call_user_func_array()'' –

+1

@MichaelBerkowski'的警告之前得到一個未定義的屬性'Test :: $ arrhandlers':hehe,是的,包括NOTICE編輯,再次同步;)我剛剛刪除了它,它感覺太像一個普通的副本;) – Wrikken

+1

它應該是'call_user_func_array($ this-> arrHandlers [$ action],$ data);'。 –

回答

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

相關問題