How to pass parameters to PHP function?

PHPz
Release: 2024-04-10 17:21:02
Original
492 people have browsed it

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.

如何传递参数到 PHP 函数?

#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
Copy after login

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
Copy after login

Practical case

Suppose there is a functioncalculateTotal(), used to calculate the total amount of the shopping cart:

function calculateTotal($items) { $total = 0; foreach ($items as $item) { $total += $item['price']; } return $total; }
Copy after login

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";
Copy after login

Output:

Total amount: 45
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!