PHP Advanced Programming-Function-Zheng Aqi_PHP Tutorial
1.php function
1. User-defined function
function function name ([ $parameter,[,…]])
{
//Function code
}
Note: The function name cannot have the same name as a system function or a function that has been defined by the user.
$parameter is a function parameter. A function generally can have 0 or more parameters.
2. Passing of parameters
Parameters are passed by value. For example, the func() function defined earlier is passed by the variable $ The values of a and $b are passed. Passing parameters by value does not change the value outside the function because the parameter value inside the function changes.
function color(&$col) //Define function color()
{
$col="yellow";
}
$blue="blue";
color($blue); //Call function color(), parameters use Variable $blue
echo $blue; //Output "yellow"
?>
3. Scope of function variables
Variables defined in the main program and in the function The variables defined in are all local variables. Variables defined in a function can only be used inside the function. Variables
defined in the main program can only be used in the main program, not in functions.
function sum()
{
$count=2;
}
sum();
echo $count;
?>
Since the variables in the function cannot act outside the function, so An error occurred when running the above, prompting that the $count variable is undefined.
4. Return value of function
When a function is declared, using the return statement in the function code can immediately end the running of the function. When the program returns, the next statement of the function is called.
function my_function($a=1)
{
echo $a;
return; //End the running of the function, the following statements will not be executed
$a++;
echo $a;
}
my_function() ; //Output 1
?>
Interrupting functions is not a common function of the return statement. Many functions use the return statement to return a value to interact with the code that calls them. The return value of a function can be of any type, including list objects
5. Function call
can be called after the function is declared. In addition, if the function does not return value, just use the function name when calling. If a function has a return value, you can assign the function's return value to a variable.
//The function my_sort() that sorts an array in ascending order
function my_sort ($array)
{
for($i=0;$i
for($j=$i+1;$j< count($array);$j++)
{
if($array[$i]>$array[$j])
{
$tmp=$array[$j];
$array[$j]=$array[$i];
$array[$i]=$tmp;
}
}
}
return $array;
}
$arr=array(6,4,7,5,9,2); //Unsorted array
$sort_arr=my_sort($arr); //Assign the sorted array Give $sort_arr
foreach($sort_arr as $num)
echo $num; //Output 245679
?>
6. Recursive function
php supports recursion Functions, recursive functions call themselves, which can achieve the effect of looping.
Ask for 10!
For example:
function factorial($n)
{
if($n==0)
return 1; //If $n is 0, return 1
else
return $n*factorial($n1); //Recursive call until $n equals 0}
echo factorial(10); //Output 3628800
?>
Use recursion - in fact, recursion termination is given condition, otherwise the function will continue to execute until the memory is exhausted or the maximum number of calls is reached.
When using recursion, you must actually provide a recursion termination condition, otherwise the function will continue to execute until the memory is exhausted, or the maximum number of calls is reached.
7. Variable function
PHP has the concept of function variable. Adding a pair of parentheses after the variable forms a variable function.
$count();
8. System function
9. Example - Design a calculator program
function cac($a, $b, $caculate) //Define the cac function to calculate two numbers The result
{
if($caculate=="+") //If it is addition, the addition
return $a+$b;
if($caculate=="-") / /If it is subtraction
return $a-$b;
if($caculate=="*") //If it is multiplication, return product
return $a*$b;
if($caculate=="/")
{
if($b=="0") //Determine whether the divisor is 0
echo "The divisor cannot be equal to 0";
else
return $a/$b; //Divide if the divisor is not 0
}
}
if(isset($_POST['ok']))
{
$number1=$_POST['number1']; //Get number 1
$number2=$_POST['number2']; //Get number 2
$caculate=$_POST['caculate']; / /Get the operation action
//Call the is_numeric() function to determine whether the received string is a number
if(is_numeric($number1)&&is_numeric($number2))
{
//Call cac function calculation result
$answer=cac($number1,$number2,$caculate);
echo "<script>alert('".$number1.$caculate.$number2."=".$ answer."')</script>";
}
else
echo "<script>alert('The input is not a number! ')</script>";
}
?>

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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

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,

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

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.

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid
