Home  >  Article  >  Backend Development  >  How to Override Default Function Arguments in PHP While Maintaining Others?

How to Override Default Function Arguments in PHP While Maintaining Others?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 21:18:03614browse

How to Override Default Function Arguments in PHP While Maintaining Others?

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?

Overriding with Null Values

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.

Setting by Variable Name

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.

Workaround for Overriding

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn