Re: Custom function

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, Feb 16, 2011 at 09:21:20PM +0100, Peter Lind wrote:

> On 16 February 2011 21:00, Dan Schaefer <dan@xxxxxxxxxxxxxxxxxxxx> wrote:
> > In my code, I set the optional parameter to NULL and check for triple
> equals
> > "===" or "!==" to see if the variable has been passed with a value. IMO,
> > this is the safest way.
> >
> > function MyFunction($x, $y, $z=NULL) {
> > if ($z !== NULL) {
> > // Do Something
> > }
> > }
> 
> In case you're actually trying to test if a variable was passed or not
> that doesn't work (as it doesn't detect NULL passed in). Use
> func_get_args() as that gives you any and all arguments passed to the
> function, excluding defaults.

This must be my week to make enemies.

I beg to differ. If the user passes in NULL for $z or passes in nothing
for that variable, it does in fact show up as NULL. The following test
code works as indicated:

function pizza($a, $b, $c = NULL)
{
	if ($c === NULL)
		echo "c is null<br>\n";
	elseif ($c !== NULL)
		echo "c is not null. it has a value of $c<br>\n";
	else
		echo "indeterminate: c is $c<br>\n";
}   
 
pizza(1, 2, NULL);
pizza(1, 2, 3);
pizza(1, 2);

=-=-=-=-=-=-=

The responses in the first and third cases are NULL. You might be able
to argue that in the first case, where the user passed in NULL, it's
not the same as if the user passed in nothing. But I would assume that the
author considers NULL a signal value, such that if the user passed such
a value in, it would be equivalent to not passing a value for the third
parameter.

> 
> That said, if you're making use of optional parameters and need to
> check if anything was passed in, you're almost certainly doing things
> wrong.

Again, assuming you're talking about examples like the one above, I have
to disagree. Presumably, passing in an optional parameter changes the
action inside the function. Thus, you would *need* to test for its
presence. Otherwise, you would be stuck with assuming it's there,
attempting to use it on that assumption, and dealing with whatever
errors it causes when-- surprise!-- it's not there.

Paul

-- 
Paul M. Foster
http://noferblatz.com


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux