Home Backend Development PHP Tutorial PHP Advanced Programming-Function-Zheng Aqi_PHP Tutorial

PHP Advanced Programming-Function-Zheng Aqi_PHP Tutorial

Jul 21, 2016 pm 03:26 PM
function php code function name copy user programming customize advanced

1.php function
1. User-defined function

Copy code The code is as follows:

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.
Copy code The code is as follows:

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.
Copy code The code is as follows:

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.
Copy code The code is as follows:

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.
Copy code The code is as follows:

//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:
Copy code The code is as follows:

function factorial($n)
{
if($n==0)
return 1; //If $n is 0, return 1
else
return $n*factorial($n1); //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
Copy code The code is as follows:



Calculator Program







< select name="caculate">




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>";
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323878.htmlTechArticle1.php function 1. User-defined function copy code The code is as follows: function function name ([$parameter,[ ,…]]) { //Function code} Note: The function name cannot be the same as the system function or user-defined...
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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks 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.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

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

See all articles