pass a callback WITH arguments in PHP

13,748
$that = $this;

$wrapper = function() use($that) {
    return $that->my_function_name('arg1', 'arg2');
};
Share:
13,748
Emanuel Mocean
Author by

Emanuel Mocean

Updated on June 15, 2022

Comments

  • Emanuel Mocean
    Emanuel Mocean almost 2 years

    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
    Emanuel Mocean over 10 years
    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.
  • zerkms
    zerkms over 10 years
    @Emanuel Mocean: then you don't have other good choice other than creating a real method for that. public function wrapper() ...
  • Emanuel Mocean
    Emanuel Mocean over 10 years
    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
    Emanuel Mocean over 10 years
    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
    Emanuel Mocean over 10 years
    nevermind , I found a way reading ?page variable from $_GET[].