search
HomeBackend DevelopmentPHP ProblemWhat are the basic knowledge for getting started with PHP functions?

What are the basic knowledge for getting started with PHP functions?

Recommended tutorial: "php tutorial"

What are the basic knowledge for getting started with PHP functions?

The basic knowledge of getting started with PHP functions are:

1. Function declaration

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

2 , Use a double-layer for loop to output the table

function table(){
echo "<table align=&#39;center&#39; border=&#39;1px&#39; width=&#39;600px&#39;>";
echo "<caption><h1 id="通过函数输出表格">通过函数输出表格</h1></caption>";
for($out=0;$out<10;$out++){
$bgcolor = $out%2 == 0 ? "#FFFFFF" : "#DDDDDD";
echo "<tr bgcolor=".$bgcolor.">";
for($in=0;$in<10;$in++){
echo "<td>".$out*10+$in."</td>";
}
echo "</tr>";
}
echo "</table>";
}

3. Rewrite the function tabel()

function table($tableName,$rows,$cols){
echo "<table align=&#39;center&#39; border=&#39;1px&#39; width=&#39;600px&#39;>";
echo "<caption><h1 id="tableName">$tableName</h1></caption>";
for($out=0;$out<$rows;$out++){
$bgcolor = $out%2 == 0 ? "#FFFFFF" : "#DDDDDD";
echo "<tr bgcolor=".$bgcolor.">";
for($in=0;$in<$cols;$in++){
echo "<td>".($out*$cols+$in)."</td>";
}
echo "</tr>";
}
echo "</table>";
}
table("此时你是我的唯一",5,3);

4. The range of PHP variables (divided into Local variables and global variables)

Local variables are also called internal variables. They are variables declared inside a function, and their scope is limited to the inside of the function.

      Local variables can be divided into dynamic storage types and static storage types in terms of storage methods. Local variables in a function, if specifically declared as a static storage category, will allocate storage space dynamically by default.

The internal dynamic variables are automatically released after the function call. If you want the internal variables to remain in memory after the function is executed, you should use static variables. After the function is executed, the static variables will not disappear, but are shared among all calls to the function. That is, when the function is executed again, the static variables will continue to operate from the previous results, and will only be used during the execution of the script. The period function is initialized the first time it is called. To declare a function variable as static, the keyword static is required. Understand it yourself!

function demo($one){
$two = $one;
echo "在函数内部执行:$two+$one=".($two+$one)."<br/>";
}
demo(200);
echo "在函数外部执行:$two+$one=".($two+$one);   //非法访问

Global variables are also called external variables, which are defined outside the function. They start from the definition of their scope variables and end at the end of this program text.

If you want to use a global variable in a function, you must use the global keyword to define the target variable to tell the function body that this variable is a global variable.

$one = 200;
$two = 100;
function demo(){
//在函数内部使用global关键字加载全局变量$one和$two
global $one,$two;
echo "运算结果:$two+$one=".($two+$one)."<br/>"; //300
echo "运算结果:".($GLOBAL[&#39;two&#39;]+$GLOBAL[&#39;one&#39;])."<br/>"; 
 
}

5. Types of PHP function parameters

(1) Functions with regular parameters

string example(string name,int age,double height)

(2) Functions with pseudo-type parameters:

PHP pseudo-types: mixed number callback Three types

mixed funName(mixed $args)

number funName(number $args)

(3) Function that refers to parameters:

If there are parameters modified with "&" in the formal parameters of the function, the function is called A variable must be passed to this parameter instead of a value.

void funName(array $&arg)

(4) Functions with default parameters:

The default value must be a constant expression, not a variable , class members or function calls. PHP allows using arrays and the special type NULL as default parameters.

mixed funName(string name[,string value[,int age]]) // 在参数列表中出现使用[]描述的参数
function person($name="张三",$age=20,$sex="男"){
echo "我的名字是:{$name},我的年龄是{$age},我的性别是{$sex}<br/>";
}

(5) Function with variable number of parameters:

func_get_args();//Return all parameters of the function passed to the script as an array

func_num_args();//Return the total number of parameters

mixed func_get_arg(int $arg_num);//Return a certain number in the parameter list Item (0...)

(6)mixed funName(string arg[,string ...])Callback function: The function parameter is a function

mixed funName(callback arg) //Use pseudo-type callback in the parameter list to describe the variable function, use the variable function declaration and apply the callback function, with the help of call_user_func_array() function customization Callback functions, class static functions and object method callbacks;

//变量函数不能用于语言结构,例如echo()
//print()、unset()、isset()、empty()
//include()、require()及类似的语句       
        function one($a,$b){
return $a+$b;
}
function two($a,$b){
return $a+$b+$b*$b;
}
function three($a,$b){
rerurn $a*$a*$a+$b*$b*$b;
}
$result = "one";
//$result = "two";
//$result = "three";
echo $result(1,2);
function filter($fun){
$fun();
}
function test(){
echo "haha!";
}
function test2(){
echo "houhou!";
}
filter("test");
filter("test2");//haha!houhou!
function fun($msg1,$msg2){
echo &#39;$msg1=&#39;.$msg1;
echo &#39;<br/>&#39;;
echo &#39;$msg2=&#39;.$msg2;
}
call_user_func_array(&#39;fun&#39;,array(&#39;Lamp&#39;,&#39;兄弟连&#39;));
//类静态调用和对象的方法调用
class Demo{
static function fun($msg1,$msg2){
echo &#39;$msg1=&#39;.$msg1;
echo &#39;<br/>&#39;;
echo &#39;$msg2=&#39;.$msg2;
}
}
class Test{
function fun($msg1,$msg2){
echo &#39;$msg1=&#39;.$msg1;
echo &#39;<br/>&#39;;
echo &#39;$msg2=&#39;.$msg2;
}
}
//类静态调用
call_user_func_array(array(&#39;Demo&#39;,&#39;fun&#39;),array(&#39;Lamp&#39;,&#39;兄弟连&#39;));
//对象的方法调用
call_user_func_array(array(new Test(),&#39;fun&#39;),array(&#39;Lamp&#39;,&#39;兄弟连&#39;));

callback("function name string"); //Callback global function

callback(array("Class name string", "Static method name string in class"));//Call back the static member method in the class

callback(array(Object reference, "Method name string in object");//Static member method in callback object

Recursive function: function calls itself

6. Use self Defining a function library

Function library is not a PHP syntax for defining functions, but a design pattern during programming. Functions are modules of structured programming and are the most important core to achieve code reuse .In order to better organize the code so that customized functions can be used in multiple files in the same project, multiple customized functions are usually organized into the same file or multiple files. These files collect function definitions It is the created PHP function library. If you want to use the functions defined in these files in a PHP script, you need to use a function among include, require, include_once, and require_once to load the function library file into the script program.

The include and require statements both include and run the specified file. The difference is that for the include statement, the file must be read and evaluated every time when executing it; while for require, the file only

is processed once (in fact, the file content replaces the require statement), which means that if the code may be executed multiple times, it is more efficient to use require. In addition, if you read a different file each time the code is executed, or have a loop that iterates through a set of

files, use the include statement.

require is used like require("MyRequireFile.php");. This function is usually placed at the front of the PHP program. Before the PHP program is executed, it will first read in the file specified by require and make it a part of the PHP program web page. Commonly used functions can also be introduced into web pages in this way.

include Use methods such as include("MyIncludeFile.php");. This function is generally placed in the processing part of flow control. The PHP program webpage only reads the include file when it reads it. In this way, the process of program execution can be simplified.

The two of them have exactly the same purpose, and it does not necessarily have to be which one is placed at the front and which one is placed in the middle. The most fundamental difference between them is the way they handle errors.

require If there is an error in a file, the program will interrupt execution and display a fatal error

include If there is an error in a file, the program will not end but will continue to execute. and displays a warning error.

Recommended related articles: "php graphic tutorial"

The above is the detailed content of What are the basic knowledge for getting started with 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools