PHP function usage tutorial

WBOY
Release: 2024-04-10 17:45:02
Original
907 people have browsed it

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 函数使用教程

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

Calling a function

To call a function, use its name and parentheses, like this:

greet("John"); // 输出:"Hello, John!"
Copy after login

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

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

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

The above is the detailed content of PHP function usage tutorial. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template