Home Backend Development PHP Tutorial PHP tutorial: PHP custom function application

PHP tutorial: PHP custom function application

Jun 26, 2017 am 11:09 AM
php function application Tutorial customize

Definition of function: A function is an encapsulated block of code that can be called at any time. There are two types of functions in PHP: Custom functions and system functions.

Custom function syntax format:

function function name ([parameter 1, [parameter 2]....])

{

function Body (program content description)

[return return value;]

}

Note: The things in [] are optional

Customized The name of the function:

  1. It is the identification name of the function in the program code. The function name can be any character starting with a letter or underscore followed by zero or more letters, underscores and numbers. string.

  2. Conform to the naming rules of variable names

  3. Function names are not case-sensitive.

  4. The function name cannot be repeated, and the declared function cannot be used when naming the function (this is different from the naming of variables, variables can overwrite the previous variable name, but functions cannot), and PHP system functionName.

The difference between function names and variable names:

Variable names are strictly case-sensitive, while function names are not case-sensitive.

Parameters (can be divided into formal parameters and actual parameters):

The so-called parameters are: used to pass values ​​from outside the function into the function body and used for calculation and processing.

The parameters are separated by ",". When the function does not require any values ​​to be passed in, the parameters can be omitted.

Formal parameters: When declaring a function, the expression in parentheses after the function name is called a formal parameter.

function table (formal parameter 1, formal parameter 2) {}

Actual parameters: The expression in parentheses after the called function name is called an actual parameter.

table (actual parameter 1, actual parameter 2);

The actual parameters and formal parameters need to pass data in order.

function table2($rows,$cols,$color='yellow')
{
    echo &#39;<table border="1" bgcolor="&#39;.$color.&#39;">&#39;;
    for($i = 0;$i < $rows;$i++){
        echo &#39;<tr>&#39;;
        for($n = 0;$n <$cols;$n++){
            echo &#39;<td>&#39;.($i*$rows+$n).&#39;</td>&#39;;
        }
        echo &#39;</tr>&#39;;
    }
}
table2(10,10,&#39;red&#39;);
Copy after login

Note: Among function parameters, those without default values ​​are placed at the front, and those with default values ​​are placed at the back of the parameter list.

table2($rows,$cols,$color = 'yellow')

Return value:

When calling a function and you need it to return some values, then you need to This is implemented using the return statement in the function body.

The format is as follows:

return return value; //The return value can be a variable or an expression

exit(); //No return value void

The return statement has the following two functions when used in the function body:

  1. The return statement can return any value determined in the function body to the function caller.

  2. Return program control to the caller's scope, that is, exit the function. If a return statement is executed in a function, the statements following it will not be executed.

Explanation: If the function does not return a value, it can only be regarded as an execution process. It is not enough to just rely on the function to do something. Sometimes it is necessary to do something in the program script

Use the result after function execution. Due to the difference in the scope of variables, the script program calling the function cannot directly use the information in the function body, but can pass data to the caller through the keyword return.

echo and return:

echo is directly output to the browser, cannot be reprocessed, and cannot be assigned to variables

return can be assigned to variables, which are temporary containers of data ( return returns a value and waits for a variable to receive it)

Note: 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 can be The name is used as the value returned by the function. (At this time, when calling the function, the value after return will not work (the value of return has been returned to the location where the function was called, and the output before return can still be output), because it has become a certain value and cannot be used with funName (); Output, echo funName() is required to output)

<?php
header("content-type:text/html;charset=utf-8");
echo show();
echo &#39;<hr>&#39;;

function show()
{
    echo &#39;ccc&#39;;
    return &#39;aaa&#39;;
    //return所在行之后的代码不会执行
    echo 111;
}

//函数的调用,不会将return后面的值返回
show();
echo &#39;<hr>&#39;;

//return返回的值 需要一个变量来接收它
$result = show();
echo $result;
echo &#39;<hr>&#39;;

//也可以直接输出 函数名称
echo show();
echo &#39;<hr>&#39;;
Copy after login

Output result:


cccaaa


ccc


cccaaa


cccaaa

Function call:

Format: function name ();

Description: table();

  1. Whether it is a custom function or a system function, if the function is not called, it will not be executed.

  2. 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.

  3. In PHP, you can call the function after the declaration of the function, you can also call it before the declaration of the function, and you can also call the function within the function.

Camel case nomenclature:

function showInfo()
{
}
function ShowInfo()
{
}
Copy after login

Judge whether the function exists: function_exists()

if(function_exists(&#39;table&#39;)){
    echo &#39;table&#39;;
}else{
    echo &#39;table函数不存在,请先定义table函数&#39;;
}
Copy after login

PHP

Range of variables:

  • 局部变量

  • 全局变量

  • 静态变量

<?php
$username = &#39;shifang&#39;;
function stu()
{
    $name = &#39;libai&#39;;
    echo $name;
    //无法调用外部的$username,而在函数体内也没有声明$username
10   echo $username;
    echo &#39;xxxx&#39;;
}

stu();
//函数体外无法调用函数体内的变量
16.echo $name;
echo $username;
Copy after login

结果:

libai

Notice: Undefined variable: username in D:\xampp\htdocs\89\Exercise\2016-7-28 PHP function\007quanju.php on line 10

xxxx

Notice: Undefined variable: name in D:\xampp\htdocs\89\Exercise\2016-7-28 PHP function\007quanju.php on line 16

shifang

在PHP的页面中声明的变量,叫“全局变量”.

函数内的变量叫“局部变量”.

二者没有半毛钱关系:函数内的变量,外部无法调用,函数外的变量,函数无法调用

(某戏班子到某学校唱戏,两者的花名册都不可相互调用)

静态变量:

  • PHP支持声明函数变量为静态的(static)。

  • 一个静态变量在所有对该函数的调用之间共享,并且仅在脚本的执行期间函数第一次被调用时被初始化。

  • 要声明函数变量为静态的用关键字static,通常,静态变量的第一次使用时赋予一个初始值。

<?php
function tongji()
{
    static $n = 0;
    echo $n;
    $n++;
}
tongji();
tongji();
tongji();
echo &#39;<hr>&#39;;

function jishu()
{
    $m = 0;
    echo $m;
    $m++;
}
jishu();
jishu();
jishu();
Copy after login

输出结果:
0123


00000


The above is the detailed content of PHP tutorial: PHP custom function application. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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

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

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,

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