On 16 February 2011 21:45, Adam Richardson <simples...@gmail.com> wrote: > On Wed, Feb 16, 2011 at 3:21 PM, Peter Lind <peter.e.l...@gmail.com> wrote: > >> On 16 February 2011 21:00, Dan Schaefer <d...@performanceadmin.com> 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. >> > > I'm not sure what you're saying here, Peter? Are you saying that the code > wouldn't detect if $z was set to NULL by the calling code or by the default? > I believe the point would be that no matter the case, the check would still > perform the same task. > > Maybe I misunderstood (sorry.)
The point is the poster seemed to suggest the safest way to use optional parameters was to use null as the default value and use === null to check against the optional parameter - as a way to check if anything was passed in or not. I just pointed out that that would fail to check for a null passed in and that func_get_args() would be a better match. You're obviously right that the check inside the function would work the same whether null was passed in or the value was defaulted to null. > >> >> 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. >> > > I sometimes use this approach. PHP doesn't to my knowledge allow you to use > function calls within defaults. There are times that I want the default to > be the result of a function, and to accomplish this, I'll often set the > default to null, then check for the null and carry out the function within. > > Is there a better solution? As noted in the post, func_get_args will show any and all (at least on my 5.3.3 install and 5.2.6 install) values passed in to the function - hence it will also show if no parameter was passed in (and is thus safer than relying on the default value). That noted, I don't think checking if a value was passed in is good design - I think the function should be ignorant of what is passed to it. But that's just me :) Regards Peter -- <hype> WWW: plphp.dk / plind.dk LinkedIn: plind BeWelcome/Couchsurfing: Fake51 Twitter: kafe15 </hype> -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php