473,800 Members | 2,523 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing arguments to callbacks

No point re-inventing the wheel, so thought I'd see if
anybody's got some good example code kicking around.

(Please excuse trivial syntactical errors, it's all coming
off the top of my head).

Say I have a function thus:

function munge($a) {
return ($a * 2);
}

Now I extend it with a callback:

function munge($a, $callback = NULL) {
if ($callback != NULL) {
$callback($a);
}
return ($a * 2);
}

function add_two ($in) {
return ($in + 2);
}

then I would call munge(3, 'add_two'); to get 10.

Q1. Is testing callback against NULL a sensible way of implementing an
optional callback?
Q1a. Should I replace it with an is_callable() or function_exists (), or
augment it with one, and which of these two makes more sense here?
(I'm guessing replace with is_callable()).

I now want to introduce another callback:

function add_var($in, $var) {
return ($in + $var);
}
so that I can call
munge(3);
munge(3, 'add_two');
munge(3, 'add_var', 1);
to get results of 6, 10, and 8 respectively.

And, of course, I want to have the number of parameters sent to the
callback to be arbitrary.

So, this line of thought leads me to call_user_func_ array();

function munge($a, $callback = NULL, $callback_args = NULL) {
if is_callable($ca llback) {
if is_array($callb ack_args)
call_user_func_ array($callback , $callback_args) ;
else
$callback($a);
}
return ($a * 2);
}

and I call
munge(3, 'add_var', array(1));
and
munge(3, 'complicated', array(1,2,3));
where complicated() is a function taking 4 parameters.

Q2. How does that look, PHP people?
Q2A. Would you add another couple of lines with "if isset" to allow the
use of call_user_func( ) for callbacks that only take two parameters?

Apr 20 '06 #1
2 4622
> Q1. Is testing callback against NULL a sensible way of implementing an
optional callback?
Yes, null is fine as default value in this case, but I would use isnull()
instead of a plain compare.
Q2. How does that look, PHP people?
You don't have to pass an array. PHP implements variable length argument
lists. Have a look at
http://www.php.net/manual/en/functio...iable-arg-list
and use func_get_args() to retrieve a variable number of arguments. Your
function could look like this (exceptions need PHP 5):

function munge($a,$callb ack=NULL)
{
if (isnull($callba ck)) return $a*2; // default
if (!is_callable($ callback)) throw new Exception('Inva lid callback');
$args=get_func_ args();
$args=(count($a rgs)>2) ? array_slice($ar gs,2) : array();
return call_user_func_ array($callback ,$args);
}
Q2A. Would you add another couple of lines with "if isset" to allow the
use of call_user_func( ) for callbacks that only take two parameters?


No. Definitely not.
Apr 21 '06 #2
F Laupretre wrote:

<snip>

Thanks for the feedback.
and use func_get_args() to retrieve a variable number of arguments. Your
Yes, I thought about this but felt that if you are going to do this:
$args=get_func_ args();
$args=(count($a rgs)>2) ? array_slice($ar gs,2) : array();
return call_user_func_ array($callback ,$args);


you might as well just pass an array in anyway. Not sure now.
Apr 21 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
14824
by: Raphael Bauduin | last post by:
Hi, I'm working with mozilla, building a little XUL app. I have a datasource, and want to display a message once it is loaded (datasource.loaded is true). So, I thought to use timouts, but as the code to execute is passed as a string, I cannot pass local variable to this code. Anyone has a suggestion?
3
14956
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
3
1592
by: johny smith | last post by:
I am having trouble with a basic concept and need some help. What I want to do is upon construction of an object I want to pass in a callback function name with an argument. The class then stores that callback function. At an appropriate time, the callback function is called with the argument. I created an example that illustrates this, but it does not work and don't really understand why.
8
11838
by: dakman | last post by:
Recently, I have been needing to do this alot and I can never find a way around it, the main reason I want to do this is because for example in the application I am making right now, it creates a grid of buttons in a loop and they all have the same purpose so they need to call the same method, within this method they need to change the background color of the button clicked, I've tried stuff like... button = lambda: self.fill(button) ...
39
7683
by: Mike MacSween | last post by:
Just spent a happy 10 mins trying to understand a function I wrote sometime ago. Then remembered that arguments are passed by reference, by default. Does the fact that this slowed me down indicate: a) That I don't know enough b) Passing arguments by ref is bad
9
5068
by: Mikhail Teterin | last post by:
Hello! I'd like to have a variable of a pointer-to-function type. The two possible values are of type (*)(FILE *) and (*)(void *). For example: getter = straight ? fgetc : gzgetc; nextchar = getter(file); What type should I give to `getter' so that the compiler does not issue
9
3346
by: zholthran | last post by:
Hi folks, after reading several threads on this issue (-> subject) I fear that I got a problem that cannot easily be solved by the offered workarounds in an acceptable way, at least not with my limited c & c++ experience. Maybe some of you can help. the problem: I need several instances of a class whose (non-static!) methods should serve as callbacks for a dll (which can' be manipulated/adapted in any
2
4247
by: william.w.oneill | last post by:
I have an application that takes a few command line parameters. As recommended by others in this group, I'm using a named mutex to ensure that only one instance of the application is running. My question is how to elegantly pass a command line parameter from Instance_B to Instance_A where Instance_A was running prior to Instance_B. For example, the user can launch the program by passing a file name as a command line argument. The program...
40
2371
by: Angus | last post by:
Hello I am writing a library which will write data to a user defined callback function. The function the user of my library will supply is: int (*callbackfunction)(const char*); In my libary do I create a function where user passes this callback function? How would I define the function?
0
9550
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10501
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10032
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7574
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5603
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.