PHP functions can pass values through parameters, which are divided into pass by value and pass by reference: pass by value: modification of parameters within the function will not affect the original value; pass by reference: modification of parameters within the function will affect the original value. In addition, arrays can also be passed as parameters for operations such as calculating the sum of data.
#How to pass parameters to PHP function?
In PHP, you can pass values through function parameters. Parameters are like variables, stored inside the function and can be used by the function. When passing parameters, you can pass them by value or by reference.
Pass by value
Passing by value creates a copy of the parameter value. When the function makes modifications to the copy, the original value is not affected.
function addFive($number) { $number += 5; } $num = 10; addFive($num); echo $num; // 输出:10
Pass by reference
Passing by reference does not create a copy of the parameter value. When a function modifies a parameter value, the original value is also modified.
function addFiveByReference(&$number) { $number += 5; } $num = 10; addFiveByReference($num); echo $num; // 输出:15
Practical case
Suppose there is a function calculateTotal()
, used to calculate the total amount of the shopping cart:
function calculateTotal($items) { $total = 0; foreach ($items as $item) { $total += $item['price']; } return $total; }
To calculate the total amount of all items in the shopping cart, you can call the function as follows:
$items = [ ['name' => 'Item 1', 'price' => 10], ['name' => 'Item 2', 'price' => 15], ['name' => 'Item 3', 'price' => 20], ]; $total = calculateTotal($items); echo "Total amount: $total";
Output:
Total amount: 45
The above is the detailed content of How to pass parameters to PHP function?. For more information, please follow other related articles on the PHP Chinese website!