Yep, I had the same issue pop up when connecting to ldap inside functions to do things like test for membership. Here's what I came up with, adjusted to connect to our database
function skeletor(){
# Argument list. args in [] are optional
# $grp, $uid, [$link]
$argc = func_num_args();
# Just change the numbers for a different number of args.
if ($argc<2||$argc>3) die("2 or 3 parameters only");
# Args in order are assigned.
$grp = func_get_arg(0);
$uid = func_get_arg(1);
# This is the optional arg. It may or may not be set.
# Note that the "default" value setting won't really work here,
# Since the third variable is, in fact, a handle to a system
# resource (database connection) and we can't really have a default
# resource, because we can't open a connection in a function
# declaration.
# So, in this case, we connect to the server anonymously
# so we can run our query.
if ($argc==3) $link = func_get_arg(2);
else {
include_once "database/connect.inc";
$link = dblink();
}
# Remainder of function goes here...
}
That way, if I'm in a long script with a connection already in existence, I can just do:
if (skeletor("arg1","arg2",$link)) print "booyeah";
but if I', in a short script with no connection of its own, I can just do:
if (skeletor("arg1","arg2")) Print "no way!";