Overriding Default Function Arguments in PHP
PHP functions support the use of default arguments to set fallback values when invoking the function. However, setting a specific argument while maintaining the default for its preceding arguments can be challenging.
Consider the following function:
<code class="php">function foo($blah, $x = "some value", $y = "some other value") { }</code>
The default arguments for $x and $y are "some value" and "some other value," respectively. But what if you want to override the default value for $y while using the default for $x?
Attempts to override the default using null, such as:
<code class="php">foo("blah", null, "test"); // Does not work</code>
or
<code class="php">foo("blah", "", "test"); // Does not work</code>
will not yield the desired result.
Another approach, assigning the default variable to a named variable, like:
<code class="php">foo("blah", $x, $y = "test");</code>
also fails to override the default.
To overcome this challenge, modify 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>
This allows you to make calls like:
<code class="php">foo('blah', null, 'non-default y value');</code>
and still maintain the default value for $x.
Note: Default arguments only work as the last arguments to the function. Omitting a parameter and overriding a following parameter is not possible when declaring default values within the function definition.
The above is the detailed content of How to Override Default Function Arguments in PHP While Maintaining Others?. For more information, please follow other related articles on the PHP Chinese website!