Home > Backend Development > PHP Tutorial > How to set default parameters in PHP function?

How to set default parameters in PHP function?

王林
Release: 2024-04-10 16:54:02
Original
1126 people have browsed it

Yes, PHP allows setting default values ​​in function parameters. Syntax: Parameter type declaration is followed by assignment operator (=) and default value. Practical example: Make the greet() function more flexible by setting the default name parameter. Note: Default parameters must be placed at the end of the parameter list. Parameters without an explicitly specified default value are required. The type declaration must precede the default value.

如何在 PHP 函数中设置默认参数?

Setting Default Parameters in PHP Functions

Default Parameters allows you to specify default values ​​for function parameters so that they can be used without passing the parameters are used. This improves the readability and flexibility of the function.

Syntax

To set a default parameter, use the assignment operator (=) and the default value after the parameter type declaration:

function funcName(int $param1 = 10, string $param2 = "Default Value") {
    // 函数代码
}
Copy after login

Practical Case

Suppose we have a function greet(), which requires a name parameter and prints a greeting containing the name:

function greet($name) {
    echo "Hello, $name!" . PHP_EOL;
}
Copy after login

We can make this function more flexible by setting default parameters as follows:

function greet($name = "World") {
    echo "Hello, $name!" . PHP_EOL;
}
Copy after login

Now, when we call the greet() function, if we do not pass the name parameter, it will Use the default value "World":

greet(); // 输出:"Hello, World!"
Copy after login

However, if we pass in a name parameter, it will override the default value:

greet("John Doe"); // 输出:"Hello, John Doe!"
Copy after login

Notes

  • Default parameters must appear at the end of the function parameter list.
  • If a parameter does not explicitly specify a default value, the parameter is required.
  • If a parameter contains both a type declaration and a default value, the type declaration must be specified first.

The above is the detailed content of How to set default parameters in PHP function?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template