Home Backend Development PHP Problem What is the usage of function keyword in php

What is the usage of function keyword in php

Feb 10, 2022 pm 05:37 PM
function php Keywords

function is a keyword in php, used for users to declare custom functions. The syntax is "function function name ([parameter 1, parameter 2, ..., parameter n]) {function body; [ return return value;]}".

What is the usage of function keyword in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

PHP functions can be divided into two types, namely PHP's predefined functions and user-defined functions. Users can directly use predefined functions in their own programs or PHP files. PHP provides a large number of feature-rich predefined functions for PHP developers to use, which greatly improves development efficiency. Custom functions are functional modules used by developers to solve specific needs.

And function is the keyword used to declare custom functions in PHP.

To declare a custom function in PHP, you can use the following syntax format:

function 函数名 ([参数1, 参数2, ..., 参数n]){
    函数体;
    [return 返回值;]
}
Copy after login

The syntax format of the function is as follows:

  • The first line of each function is the function header, which consists of three parts: the keyword function declaring the function, the function name, and the parameter list. Each part completes a specific function;

  • Each custom function must be declared using the function keyword;

  • The function name can represent the entire function, and the function can be named any name, as long as the naming rules for variable names are followed. Can. Each function has a unique name, but it should be noted that function overloading cannot be used in PHP, so functions with the same name cannot be defined, including the same name as the system function;

  • When declaring a function, the parentheses "()" after the function name are also required. The parentheses contain a set of acceptable parameter lists. The parameters are the declared variables, and then the variables can be passed to when calling the function. function. The parameter list can be empty or have one or more parameters. Use commas to separate multiple parameters;

  • You need to use a space between the keyword "function" and the function name. Separated, and there is no need to use spaces to separate the function name and the parentheses wrapping the parameter list. Of course, adding spaces will not cause an error;

  • The function body is located after the function header and needs to be Use curly brackets "{}" to wrap it. All the work of a function is done in the function body. After the function is called, the first statement in the function body is first executed, and execution ends after the return statement or the outermost brace "}", and returns to the place where the function was called. Any valid PHP code can be used in the function body, and even the definition of other functions or classes can be declared in the function body;

  • Use the keyword return to return a Value or expression, when the program executes to the return statement, the expression will be calculated, and then return to the place where the function was called to continue execution.

Because the parameter list and return value are not required when defining a function, but other parts are required, there are usually the following ways to declare a function.

1) There is no parameter list when declaring a function:

function 函数名(){
    函数体;
    return 返回值;
}
Copy after login

2) There is no return value when declaring a function:

function 函数名(参数1, 参数2, ..., 参数n){
    函数体;
}
Copy after login

3) There is no need when declaring a function Parameter list and return value:

function 函数名(){
    函数体;
}
Copy after login

Call of function

Whether it is a custom function or a system function, if the function is not called, it will not be executed. Just call the function using its name and parameter list wherever you need to use it.

After the function is called, it starts executing the code in the function body. After the execution is completed, it returns to the calling position and continues downward execution. Therefore, the function name can summarize the following three functions when the function is called.

  • You can call the function through the function name and let the code of the function body run. The function body will be executed several times after calling it several times;

  • If the function has a parameter list, you can also pass the corresponding value to the parameter in parentheses after the function name, and use the parameters in the function body to change the execution behavior of the internal code of the function;

  • If the function has a return value, when the function is executed, the value after return will be returned to the location where the function was called, so that the function name can be used as the value returned by the function.

Tip: As long as the declared function is visible in the script, it can be called anywhere in the script through the function name. In PHP, it can be called after the function is declared. You can also call a function before its declaration, or you can call a function within a function.

[Example] When we explain the for loop, the program that prints the multiplication table is encapsulated into a function. The code is as follows:

<?php
    function table(){       //定义函数
        for ($i = 1; $i <= 9; $i++) {
            for ($j = 1; $j <= $i; $j++) {
                echo $j.&#39; * &#39;.$i.&#39; = &#39;.$i*$j.&#39;  &#39;;
            }
            echo &#39;<br>&#39;;
        }
    }
    table();//调用函数
?>
Copy after login

The running results are as follows:

1 * 1 = 1 
1 * 2 = 2  2 * 2 = 4 
1 * 3 = 3  2 * 3 = 6  3 * 3 = 9 
1 * 4 = 4  2 * 4 = 8  3 * 4 = 12  4 * 4 = 16 
1 * 5 = 5  2 * 5 = 10  3 * 5 = 15  4 * 5 = 20  5 * 5 = 25 
1 * 6 = 6  2 * 6 = 12  3 * 6 = 18  4 * 6 = 24  5 * 6 = 30  6 * 6 = 36 
1 * 7 = 7  2 * 7 = 14  3 * 7 = 21  4 * 7 = 28  5 * 7 = 35  6 * 7 = 42  7 * 7 = 49 
1 * 8 = 8  2 * 8 = 16  3 * 8 = 24  4 * 8 = 32  5 * 8 = 40  6 * 8 = 48  7 * 8 = 56  8 * 8 = 64 
1 * 9 = 9  2 * 9 = 18  3 * 9 = 27  4 * 9 = 36  5 * 9 = 45  6 * 9 = 54  7 * 9 = 63  8 * 9 = 72  9 * 9 = 81
Copy after login

[Example] Let's define a function to implement simple addition operation. The code is as follows:

<?php
    function add($num1,$num2){
        $a = $num1 + $num2;
        return $a;
    }
    $sum = add(11,5);
    echo &#39;$sum = &#39;.$sum.&#39;<br>&#39;;
    echo &#39;6 + 33 =&#39;.add(6,33).&#39;<br>&#39;;
    echo &#39;42 + 21 =&#39;.add(42,21).&#39;<br>&#39;;
    echo &#39;167 + 153 =&#39;.add(167,153);
?>
Copy after login

The running results are as follows:

$sum = 16
6 + 33 =39
42 + 21 =63
167 + 153 =320
Copy after login

Recommended learning: " PHP video tutorial

The above is the detailed content of What is the usage of function keyword in php. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles