The elements of a PHP function include: Function declaration: starting with the function keyword, followed by the function name and optional parameter and return value types. Function body: Contains the block of code that defines the behavior of the function and may contain return statements.
A PHP function consists of the following basic elements:
function
keyword, followed by the function’s name, parameters (optional) and return value type (optional). function function_name(parameter1, parameter2, ...): return_type { // 函数体 }
function_name
: The unique name of the function. parameter1
, parameter2
, ...: The parameter list of the function, separated by commas. return_type
: The return value type of the function (optional), which can be void
(no return value) or any PHP data type. The function body contains the behavior code of the function, which can perform the following operations:
Consider a function that adds two numbers and returns the result:
function add_numbers($num1, $num2): int { $result = $num1 + $num2; return $result; }
To use this function, we can do this:
$x = 5; $y = 10; $sum = add_numbers($x, $y); // 调用函数并存储结果 echo $sum; // 输出结果
This will print out the sum of the two numbers, which is 15.
The above is the detailed content of What elements does a PHP function contain?. For more information, please follow other related articles on the PHP Chinese website!