Jump to content

The use of null to skip the entry of parameter values in a function


iwato

Recommended Posts

Statement: If specified, then only substrings up to the value of $limit are returned with the rest of the string being placed in the last substring. A limit of -1, 0, or null means "no limit" and, as is standard across PHP, you can use null to skip to the $flags parameter.Question: How is null entered in this case?By way of example, consider a function containing three parameters of which the last two are optional. Say, I wanted to set only the first and third parameters. Would I enter,

my_function($param_value1, null, $param_value3);

Roddy

Link to comment
Share on other sites

Statement: If specified, then only substrings up to the value of $limit are returned with the rest of the string being placed in the last substring. A limit of -1, 0, or null means "no limit" and, as is standard across PHP, you can use null to skip to the $flags parameter.Question: How is null entered in this case?By way of example, consider a function containing three parameters of which the last two are optional. Say, I wanted to set only the first and third parameters. Would I enter,
my_function($param_value1, null, $param_value3);

Roddy

This a JS question or PHP?Either way, yes, that is how you typically "skip" optional parameters. For custom functions, it really depends on how you wrote it. Sometimes skipping an optional parameter could be done by passing an empty string, for example.Basically, it just boils down to what the function is expecting, and what it's checking for. Pre-built functions will "skip" optional parameters (most of the time using default values) if you specify null.
Link to comment
Share on other sites

This a JS question or PHP?
Thank you, I was wondering what happened to it. Hopefully someone will move it to where it belongs.So, how does one write a custom function that fits the PHP mold in this regard?Roddy
Link to comment
Share on other sites

Like so:

function doSomething($requiredArgument, $optionalArgument1 = 'Default value', $optionalArgument2 = 'Another default value') {	if(is_null($optionalArgument1)) $optionalArgument1 = 'Default value';	if(is_null($optionalArgument2)) $optionalArgument2 = 'Another default value';	//rest of the code}

or for the sake of shortening, even:

function doSomething($requiredArgument, $optionalArgument1 = null, $optionalArgument2 = null) {	if(is_null($optionalArgument1)) $optionalArgument1 = 'Default value';	if(is_null($optionalArgument2)) $optionalArgument2 = 'Another default value';	//rest of the code}

Without either of these forms ("normal" coding), null is null in custom functions... it's not equivalent to "Default value".<<Moved topic>>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...