Home  >  Article  >  Backend Development  >  What are the default values ​​for PHP function parameter types?

What are the default values ​​for PHP function parameter types?

WBOY
WBOYOriginal
2024-04-10 15:48:021063browse

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.

PHP 函数参数类型的默认值是什么?

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:

  • Default values ​​can only be specified in function declarations.
  • Optional parameters with default values ​​must be at the end of the function declaration parameter list.
  • If the parameter has a default value, the parameter can be safely omitted.

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!

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