PHP function parameters can have type specifications and default values, and the return value can return a type specification value. For example, a function sum() that calculates the sum of two numbers and returns an integer takes two integer arguments, one of which has the default value "Guest".
Parameters and return values of PHP functions
Function parameters
Function parameters is the data value passed to the function. They allow functions to perform specific tasks. Parameters appear as a comma-separated list in function definitions and function calls.
function function_name(parameter1, parameter2) {}
Parameter type description
Parameters can have type specifications. The type specification specifies the expected data type of the parameter.
function sumOfNumbers(int $num1, int $num2) {}
In this example, the sumOfNumbers()
function expects two integer parameters ($num1
and $num2
).
Default parameter values
Parameters can have default values. When a function is called, if a parameter value is specified, it is used. If not specified, the default value is used.
function greetUser($name = "Guest") {}
In this example, the greetUser()
function has a default parameter $name
with the value "Guest".
Return value
The function can return a value. The return value is the data value of the function execution result. The return value is specified using the return
statement.
function function_name(): return_type {}
Return value type specification
The return value can have a type specification. The type specification specifies the expected data type of the return value.
function getSumOfNumbers(): int {}
In this example, the getSumOfNumbers()
function returns an integer.
Practical Case
Consider a function that calculates the sum of two numbers:
function sum(int $num1, int $num2): int { return $num1 + $num2; } // 调用函数 $result = sum(5, 10); // 打印结果 echo $result; // 输出 15
The above is the detailed content of Parameters and return values of PHP functions. For more information, please follow other related articles on the PHP Chinese website!