Home  >  Article  >  Backend Development  >  Syntax and structure of PHP functions

Syntax and structure of PHP functions

王林
王林Original
2024-04-13 14:09:02474browse

PHP function syntax includes function declaration (function_name and parameter list) and function body (containing the code to be executed). Functions can define a return value type, and if it is not defined, NULL is returned. Examples include calculating the sum of two numbers and checking whether a string contains another string.

PHP 函数的语法和结构

The syntax and structure of PHP function

Grammar

The syntax of PHP function is as follows:

function [修饰符] function_name([参数列表]) {
  // 函数体
}

Where:

  • [Modifier] is optional and can be public, private, protected or static.
  • function_name is the name of the function.
  • [Parameter List] is optional and contains the list of parameters accepted by the function.
  • The function body is the block of code that contains the code to be executed by the function.

Structure

PHP function consists of the following parts:

  • Function declaration: Contains function header (function, [modifier] and function_name) and parameter list.
  • Function body: Contains the code to be executed by the function.
  • Function return value: If the function defines a return value type, the function will return a value of that type. If the return type is not defined, the function returns NULL.

Practical case

Example 1:Calculate the sum of two numbers

function add($num1, $num2) {
  return $num1 + $num2;
}

$result = add(10, 15);
echo $result; // 输出:25

Example 2:Judge one Whether a string contains another string

function contains($str, $subStr) {
  return strpos($str, $subStr) !== false;
}

$contains_result = contains("Hello world", "world");
echo $contains_result ? '包含' : '不包含'; // 输出:包含

The above is the detailed content of Syntax and structure of PHP functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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