PHP There are three ways to pass function parameters: Pass by value: The function obtains a copy of the parameter, and modifications to the copy do not affect the original value. Pass by reference: The function obtains a reference to the parameter, and modifications to the copy will affect the original value. Pass optional parameters by value: You can specify a default value when the function is called, and if the parameter is not specified, the default value is used.
Function parameter passing methods in PHP
There are three ways to pass parameters in PHP functions: passing by value and passing by reference and passing optional parameters by value.
Pass by value
Pass by value means that the function actually obtains a copy of the parameter, and any modification to the copy will not affect the original value.
Syntax:
function myFunction($a) { $a += 1; }
Example:
$x = 5; myFunction($x); echo $x; // 输出: 5
Pass by reference
Passing by reference means that the function obtains a reference to the parameter, and any modification to the copy will affect the original value.
Syntax:
function myFunction(&$a) { $a += 1; }
Example:
$x = 5; myFunction($x); echo $x; // 输出: 6
Passing optional parameters by value
Passing optional arguments by value allows default values to be specified at function call time. If no parameters are specified, default values are used.
Grammar:
function myFunction($a = 5) { return $a; }
Example:
echo myFunction(); // 输出: 5 echo myFunction(10); // 输出: 10
Practical case
The following is a practical example of passing parameters by reference to find a value in an array:
function findValueInArray(&$array, $value) { foreach ($array as $key => $item) { if ($item === $value) { return $key; } } return -1; } $fruits = ['apple', 'banana', 'orange']; $index = findValueInArray($fruits, 'banana'); echo $index; // 输出: 1
The above is the detailed content of How to pass parameters to PHP functions?. For more information, please follow other related articles on the PHP Chinese website!