Home > Article > Backend Development > What are the default values for PHP function parameter types?
Parameters in PHP functions can have default values, which can be specified in the function declaration and used when omitted. Syntax: function function_name(type $parameter1 = default_value, type $parameter2 = default_value, ...): return_type. For example, function sum($a, $b = 0, $c) receives three arguments, where $b has a default value of 0. If the default value parameter is omitted, its default value is used. For example, function square($number = 10) returns the square of the number. If omitted, the default value of 10 is used.
Default value of PHP function parameter type
In PHP, functions can accept optional parameters, which can have default value. The default value is specified in the function declaration and is used when it is omitted when the function is called.
Syntax:
function function_name(type $parameter1 = default_value, type $parameter2 = default_value, ...): return_type
For example, the following function accepts three parameters, where the second parameter has a default value of 0
:
function sum($a, $b = 0, $c) { return $a + $b + $c; }
Practical case:
We write a function that accepts a number and returns its square. If no number is provided, the default value 10
is used:
function square($number = 10) { return $number * $number; } echo square(); // 输出:100 echo square(5); // 输出:25
In the above example, we called the square()
function twice. No parameters were provided on the first call, so the default value 10
was used. On the second call, we provide the number 5
as an argument.
Other notes:
The above is the detailed content of What are the default values for PHP function parameter types?. For more information, please follow other related articles on the PHP Chinese website!