1

I'm trying to make a system which handles supplied data and calls the functions assigned to them in an array with addHandler().

Code:

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

What it outputs:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given on line 13 

What I want it to output:

I like cheese 
7
  • 2
    $this->arrHandlers != $this->arrhandlers. Do you have E_NOTICE displaying in your error_reporting? You should be getting an undefined property Test::$arrhandlers before the warning about call_user_func_array() Commented Feb 17, 2014 at 20:32
  • 1
    @MichaelBerkowski: hehe, yeah, including the NOTICE edit, once again in sync ;) I've just deleted mine, it felt way too much like a plain copy ;) Commented Feb 17, 2014 at 20:34
  • 1
    It should be call_user_func_array($this->arrHandlers[$action], $data);. Commented Feb 17, 2014 at 20:34
  • @MichaelBerkowski Can't believe I didn't notice that. Added error_reporting(E_ALL) and fixed the caps mistake. This is what I now get: Notice: Array to string conversion on line 21 Array . Line 21 is echo implode(" ", func_get_args()); Commented Feb 17, 2014 at 20:37
  • Per @RocketHazmat's comment -that's the crux of it, after fixing the property casing on arrHandlers. I've tested it working with that implementation. Commented Feb 17, 2014 at 20:37

1 Answer 1

2

Working code:

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

I put 'arrhandlers' instead of 'arrHandlers' and passed $data as 'array($data)' instead of just '$data' to call_user_func_array().

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.