6

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.

Emanuel Mocean
  • 285
  • 1
  • 3
  • 8
  • Wrap it with another function (presumably anonymous) – zerkms Jan 16 '14 at 01:19
  • @zerkms - in that case the anonymous function would still get the argument from the "calling" library function. But I want to give it my own parameters. – Emanuel Mocean Jan 16 '14 at 01:29
  • Duplicate page which provides the advice found in the accepted answer below: [Callback function using variables calculated outside of it](https://stackoverflow.com/q/4588714/2943403) – mickmackusa Mar 25 '23 at 06:33

3 Answers3

11
$that = $this;

$wrapper = function() use($that) {
    return $that->my_function_name('arg1', 'arg2');
};
zerkms
  • 249,484
  • 69
  • 436
  • 539
  • It works but I think it requires php 5.3 .I am making a wordpress theme so "use" it's not ready for me yet. – Emanuel Mocean Jan 16 '14 at 01:54
  • @Emanuel Mocean: then you don't have other good choice other than creating a real method for that. `public function wrapper() ...` – zerkms Jan 16 '14 at 01:58
  • In my particular case I still have to find a way to pass the parameters to the public function wrapper because the only time I know what I want to supply as a parameter to the callback is when I pass the callback. In other words I need the "use" part to make my local variables available in the callback . – Emanuel Mocean Jan 16 '14 at 02:19
  • To be more clear: what I am trying to do is pass the "rendering" callback to the add_submenu_page Wordpress function , and give that callback a parameter so it knows what page to draw. – Emanuel Mocean Jan 16 '14 at 02:21
  • nevermind , I found a way reading ?page variable from $_GET[]. – Emanuel Mocean Jan 16 '14 at 02:26
2

There is a function called call_user_func_array.

call_user_func_array([$this, 'method'], $args);
roel
  • 1,640
  • 14
  • 13
0

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.

eggmatters
  • 1,130
  • 12
  • 28