Guilherme
Guilherme

Reputation: 1990

call_user_func inside a function in a class method doesn't work

I need to call a function that is inside of another function that is inside a class.

class Some_class extends CI_Controller {
    public function file($action){
        function add(){ 
            $content = "Content";
            $data = array('html'=>$content);
            $this->output->append_output(json_encode($data));
        }
        call_user_func($action);
    }
}

This returns nothing.

I need to call the function add(), and isn't working, even if I just put the add()rather than the call_user_func(). But the idea is call every function inside the function file().

Upvotes: 1

Views: 1269

Answers (2)

Ynhockey
Ynhockey

Reputation: 3932

While I have never personally used this function, I believe that it doesn't work because you're not returning anything.

If the function $action is supposed to return a value, then write:

return call_user_func($action);

Otherwise (if it puts a value in a param), it would require a param, which would work something like:

call_user_func($action, $param);
return $param;

Maybe I misunderstand what you're trying to do though.

Upvotes: 1

rjz
rjz

Reputation: 16510

You want to pass a callback. Say that action is a method of MyClass. You would then use:

$my_class = new MyClass();

call_user_func(array($my_class, 'action'));

Upvotes: 1

Related Questions