PHP function consists of function header, function parameters, function body and return value: function header contains function name, parameter list and optional return value type. Function parameters are variables passed into the function. The function body executes the code to be executed. A function can return a value via the return statement, the type of which is optionally specified in the function header.
A PHP function is a predefined block of code that performs a specific task. It consists of the following components:
The function header specifies the name, parameter list and return value type of the function (optional):
function function_name(argument1, argument2, ...): return_type { // 函数体 }
For example:
function greet(string $name): string { return "Hello, $name!"; }
Function parameters are variables or values that are passed to the function. They are specified in the function header, and the type and name are optional.
The function body contains the code to be executed. It is located between the function header and the curly braces {}
.
The function can return a value, specified by the return
statement. The return type is specified in the function header (optional).
Consider a function that calculates the sum of two numbers:
function sum(int $a, int $b): int { return $a + $b; } // 调用函数 $result = sum(10, 20); echo $result; // 输出: 30
void
(None) by default. The above is the detailed content of What are the components of a PHP function?. For more information, please follow other related articles on the PHP Chinese website!