Home > Article > Backend Development > How to set default parameters in PHP function?
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.
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") { // 函数代码 }
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; }
We can make this function more flexible by setting default parameters as follows:
function greet($name = "World") { echo "Hello, $name!" . PHP_EOL; }
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!"
However, if we pass in a name parameter, it will override the default value:
greet("John Doe"); // 输出:"Hello, John Doe!"
Notes
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!