PHP functions allow code to be modularized for easy reuse. To create a function, use the function keyword, specifying the function name, parameters, and function body. To call a function, use its name and arguments. Functions can accept parameters and return a value. Variables declared inside a function are in the local scope. To access global variables, you need to use the global keyword. Functions improve the readability and maintainability of your code, for example you can create a function that calculates an order total.
PHP function usage tutorial
Overview
Function is a combination of code A method of reusable modules that allows you to reuse them in different parts of your program. This article will guide you on how to use PHP functions.
Create a function
To create a function, use the function
keyword, followed by the function name, parentheses, and function body:
function greet($name) { echo "Hello, $name!"; }
Calling a function
To call a function, use its name and parentheses, like this:
greet("John"); // 输出:"Hello, John!"
Parameters and return values
Functions can accept parameters, which are values passed to it. To specify parameters, list them in parentheses, separated by commas. The function can also return a value, using return
Keyword:
function add($a, $b) { return $a + $b; } $result = add(5, 10); // $result 将变为 15
Scope
Variables declared inside the function and variables outside the function are separate. It's called the local scope of the function. To access global variables in a function, use global
Keywords:
$name = "John"; function greet() { global $name; echo "Hello, $name!"; } greet(); // 输出:"Hello, John!"
Practical Case
Using functions can make the code easier to read and maintain. For example, you can create a function that calculates the order total:
function calculateTotal($items) { $total = 0; foreach ($items as $item) { $total += $item['price'] * $item['quantity']; } return $total; } $items = [ ['price' => 10, 'quantity' => 2], ['price' => 15, 'quantity' => 1], ]; $total = calculateTotal($items); // $total 将变为 35
The above is the detailed content of PHP function usage tutorial. For more information, please follow other related articles on the PHP Chinese website!