pass a callback WITH arguments in PHP
13,748
$that = $this;
$wrapper = function() use($that) {
return $that->my_function_name('arg1', 'arg2');
};
Author by
Emanuel Mocean
Updated on June 15, 2022Comments
-
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 themy_function_name
? I have found a solution usingcreate_function
but from PHP manual I see it has security issues. -
Emanuel Mocean over 10 yearsIt 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 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 over 10 yearsIn 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 over 10 yearsTo 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 over 10 yearsnevermind , I found a way reading ?page variable from $_GET[].