PHP tutorial: PHP custom function application
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:
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.
Conform to the naming rules of variable names
Function names are not case-sensitive.
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 '<table border="1" bgcolor="'.$color.'">'; for($i = 0;$i < $rows;$i++){ echo '<tr>'; for($n = 0;$n <$cols;$n++){ echo '<td>'.($i*$rows+$n).'</td>'; } echo '</tr>'; } } table2(10,10,'red');
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:
The return statement can return any value determined in the function body to the function caller.
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 '<hr>'; function show() { echo 'ccc'; return 'aaa'; //return所在行之后的代码不会执行 echo 111; } //函数的调用,不会将return后面的值返回 show(); echo '<hr>'; //return返回的值 需要一个变量来接收它 $result = show(); echo $result; echo '<hr>'; //也可以直接输出 函数名称 echo show(); echo '<hr>';Output result:
ccc
cccaaa
cccaaaFunction call: Format: function name (); Description: table();
- Whether it is a custom function or a system function, if the function is not called, it will not be executed.
- 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.
- 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.
function showInfo() { } function ShowInfo() { }
Judge whether the function exists: function_exists()
if(function_exists('table')){ echo 'table'; }else{ echo 'table函数不存在,请先定义table函数'; }PHP
Range of variables:
局部变量
全局变量
静态变量
<?php $username = 'shifang'; function stu() { $name = 'libai'; echo $name; //无法调用外部的$username,而在函数体内也没有声明$username 10 echo $username; echo 'xxxx'; } stu(); //函数体外无法调用函数体内的变量 16.echo $name; echo $username;
结果:
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 '<hr>'; function jishu() { $m = 0; echo $m; $m++; } jishu(); jishu(); jishu();
输出结果:
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!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor