Home >Backend Development >PHP Tutorial >Parameter passing and return value types of PHP functions
Parameter passing in PHP has two methods: value passing and reference passing. The return value type can specify the returned data type. Passing by value: The function handles a copy of the parameter value, and modification of the parameter does not affect the variable of the calling function. Pass by reference: The function directly handles the address of the variable in the calling function, and modification of parameters will affect the variables of the calling function. Supported return value types include int, float, string, array, object, callable, and void.
Parameter passing and return value type of PHP function
Parameter passing
PHP functions can receive parameters using pass-by-value or pass-by-reference.
Usage:
In a function definition, use the &
symbol before the parameter name to enable passing by reference.
For example:
function addByReference(&$num) { $num++; }
Return value type
PHP functions can also specify the return value type. This means that when you return a value from a function, PHP checks the type of the value and casts it to match the specified type.
Syntax:
function function_name(param_type $param_name): return_type { // 函数代码 }
Supported types:
PHP supports the following return types:
int
: Integer float
: Floating point number string
: String array
:arrayobject
:objectcallable
:callable (function)void
: No return type##For example:
function getSum(int $a, int $b): int { return $a + $b; }
Actual case
Value passing example:
<?php $num = 10; function add($num) { $num++; } add($num); echo $num; // 输出:10,因为参数是按值传递的 ?>
Reference passing example:
Return value type example:
<?php function getGreeting(string $name): string { return "Hello, $name!"; } $greeting = getGreeting("John"); echo $greeting; // 输出:Hello, John! ?>
The above is the detailed content of Parameter passing and return value types of PHP functions. For more information, please follow other related articles on the PHP Chinese website!