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

Linda Hamilton
Release: 2024-10-30 21:18:03
Original
613 people have browsed it

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>
Copy after login

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>
Copy after login

or

<code class="php">foo("blah", "", "test"); // Does not work</code>
Copy after login

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>
Copy after login

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>
Copy after login

This allows you to make calls like:

<code class="php">foo('blah', null, 'non-default y value');</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!