PHP There are two ways to pass parameters: call by value (the parameter is passed as a copy of the value, modification within the function does not affect the original variable) and passing by reference (the address of the parameter is passed, modification within the function will affect the original variable), when needed Use reference passing when modifying the original variable. For example, when calculating the total price of the shopping cart, reference passing is required to calculate correctly.
There are two main methods of parameter passing in PHP:
1. Pass-by-Value**
In this method, the parameters are passed to the function as a copy of the value. If the parameter value is modified within the function, the value of the original variable will not be affected.
function double($number) { $number *= 2; return $number; } $num = 10; $result = double($num); echo $num; // 输出: 10 echo $result; // 输出: 20
2. Pass-by-Reference **
In pass-by-reference, the address of the parameter is passed to the function instead of the value. This means that if the parameter value is modified within the function, the value of the original variable will also be affected.
function &triple(&$number) { $number *= 3; return $number; } $num = 10; $result = &triple($num); echo $result; // 输出: 30 echo $num; // 输出: 30
Shopping cart function implementation
A function is needed to calculate the total price of all items in the shopping cart. The list of items is stored in an array, and each item has a price.
$cart = [ ['product' => 'Apple', 'price' => 1.20], ['product' => 'Orange', 'price' => 0.80] ]; function get_total_price($cart) { $total = 0; foreach ($cart as &$item) { $total += $item['price']; } return $total; } $total_price = get_total_price($cart);
In the above example, the $cart
parameter of the get_total_price
function is passed by reference. This is necessary because the function modifies the price of each item in $cart
(adding it to the total price). If called by value, these changes will not be reflected in the original shopping cart array passed to the function.
The above is the detailed content of What is the parameter passing method for PHP functions?. For more information, please follow other related articles on the PHP Chinese website!