Overriding Default Function Arguments
When declaring PHP functions with default arguments, it's important to understand how to override those values while still using the default argument for others. Consider the following function:
<code class="php">function foo($blah, $x = "some value", $y = "some other value") { // code here! }</code>
To use the default argument for $x while setting a different value for $y, the following incorrect attempts will not work:
<code class="php">foo("blah", null, "test"); foo("blah", "", "test");</code>
As they do not assign the desired default value to $x. Additionally, attempting to set the argument by variable name:
<code class="php">foo("blah", $x, $y = "test");</code>
fails to produce the expected result.
To achieve the desired behavior, consider modifying the function declaration as follows:
<code class="php">function foo($blah, $x = null, $y = null) { if (null === $x) { $x = "some value"; } if (null === $y) { $y = "some other value"; } // code here! }</code>
Now, it's possible to invoke the function with variations such as:
<code class="php">foo('blah', null, 'non-default y value');</code>
and have it set $x to the default value while overriding $y.
It's important to note that default parameters only apply to the last arguments in the function definition. If multiple parameters follow the optional parameter with the default value, it's not possible to omit one and specify the following one.
The above is the detailed content of How to Override Default Function Arguments in PHP?. For more information, please follow other related articles on the PHP Chinese website!