myFunction($a,$b = 'B',$c =''){
echo $b;
...
if I call it like this:
myFunction('a');
I get the default value of $b: B
Sometimes I want to use the first and third parameter, but not the
second. How do I do that?
myFunction('a','','c');
Sets $b to '';
myFunction('a',NULL,'c');
does not work either.
And:
myFunction('a',,'c');
is illegal.
What am I missing? Is there a shorthand for this or do I have to test $b?
Jeff
Variables with a default value should come last in the parameter list.
Refer to "default argument values" in the manual.
You don't. If you want to specify the third value, you must specify the
first and second.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstu...@attglobal.net
==================
> I have a function:
>
> myFunction($a,$b = 'B',$c =''){
>
> echo $b;
> ...
<snip>
> Sometimes I want to use the first and third parameter, but not
> the second. How do I do that?
As Jerry says, you can't actually skip the second parameter, but you
can change how your function will interpret it. For example, if you
wanted to allow `NULL' to be passed to indicate usage of a default
parameter value, you would need to implement this in the function
explicitly.
<?php
function myFunction($a, $b = 'B', $c = '') {
if (is_null($b))
$b = 'B';
/* ... */
}
?>
--
Curtis Dyer
<? $x='<? $x=%c%s%c;printf($x,39,$x,39);?>';printf($x,39,$x,39);?>
You may want to do some reading here.
http://www.php.net/manual/en/function.func-get-args.php
It may or may not be what you need but I have used it successfully in a
few situations. It you find you are using different functions vars
randomly then you may want to rethink your function design and break it
down into smaller components so you have predictable vars.
Scotty
Thanks to all.
What happened is that I have a class that I use often, and when I
expanded it I had to put the new argument at the end of the list (for
the class constructor) to keep from breaking existing code.
I see now how to proceed. Often the crystal ball of where your code
is going is a little hazy!
There's a lot to be said about passing in an associative array and
not worrying about order.
Jeff
You can get around this by using a little trick:
function myFunction($a,$b='B',$c =''){
if ($b == 'default') $b = 'B';
}
then call your new ones with
myFunction('a','default','c');
Of course, doing this does nothing more than simply calling it as
myFunction('a','B','c');
but if you do this modification with all your functions that have more
than a single default argument, then calling any of them with 'default'
will do the right thing and you won't have to remember what the
"correct" default value is.