Emanuel Mocean
Emanuel Mocean

Reputation: 295

pass a callback WITH arguments in PHP

I have a PHP library function expecting a callback with no arguments. I know I can pass an object's method with array($this , 'my_function_name') but how can I give parameters to the my_function_name? I have found a solution using create_function but from PHP manual I see it has security issues.

Upvotes: 6

Views: 24402

Answers (3)

roel
roel

Reputation: 1660

There is a function called call_user_func_array.

call_user_func_array([$this, 'method'], $args);

Upvotes: 4

eggmatters
eggmatters

Reputation: 1140

This will depend on your library functions initiation of the callback method. You mentioned that you're making a wordpress theme. WP uses the call_user_func method typically. In your library function, use this function to invoke a call back with args, wrap a methods argument when calling it:

Callback Definition:

$callbackArg = "Got here";
defined_lib_func(array($this , 'my_function_name'), $callbackArg);

Library Script:

function defined_lib_function($callback, $args) {
  call_user_func($callback, $args);
}

for multiple arguments, just pass them as an array and define your callback method to accept an array as an argument.

Upvotes: 0

zerkms
zerkms

Reputation: 254926

$that = $this;

$wrapper = function() use($that) {
    return $that->my_function_name('arg1', 'arg2');
};

Upvotes: 14

Related Questions