PHP function Syntax Definition example detailed

Source: Internet
Author: User
Tags variable scope
A function is a collection of code that accomplishes a particular function and can be divided into system functions and user functions. Users can implement a specific need by creating a custom function.

1. Function definition Syntax structure:

PHP allows the user to create a custom function using the function keyword. Syntax structure:
Function name (parameter 1, parameter 2, ...)
{
Code inside the function
}
PHP has fewer restrictions on function names, and can be any string that begins with a letter or underscore followed by a letter, underscore, or number, and is not case sensitive. The parentheses are the parameters of the function, separated by commas, and the parentheses cannot be omitted without arguments. Inside the curly braces is the function body, which is used in the body of the function to specify the return value of the function. Example:

function format_html ($text) {$text = "<u><i><b> $text </b></i></u>";//Apply Bold, The Echo $text is marked in italics and bold; Output formatted string}

2. Use the function:

Once a user function is created, it can be used like a system function, which is called by specifying a function name. If the function requires parameters, you need to specify the value of the parameter within the parentheses, and note that the type of the parameter should be consistent with the definition.
When invoking a user-defined function, you must ensure that the previous function already exists, that is, the function should first define the call. Example:

<table cellspacing=0 cellpadding=0 width "511" border=0>   <tr> <td width= "All" height=22> product name:< /TD> <td width= "292" height=22 class= "title" ><?php FORMAT_HTMI ("Enterprise Management System");?></td>   </tr > </table>

3. function return value:

Sometimes you need to use the result of function execution outside the program, and you need to specify a return value within the function using the return statement. Use the return statement to return any type of data for a function. Example:

<?php function Getdataary () {$resAry =array (95,87,79,80,62,74,90,92);//Create an array return $resAry;//Return the array} $ary = Getdataary (); The Save function returns an array of foreach ($ary as $i) echo $i. ","; Iterates through an array, outputting all numbers?>

4. function parameter passing mode:

The parameters that PHP supports are passed by value, by index, by default, and by variable argument lists.

1) pass by value:

Passing by value is the default way to pass a parameter to PHP. This method of passing creates a copy of the value of the function's external variable and assigns it to a local variable inside the function. After the function processing is complete, the value of the external variable does not change unless the outer variable scope is declared as global within the function. Example:

<?php function Passbyvalue ($number, $STR) {//By value passing parameters $number +=100;/////////////The first parameter increases $str. = "World";//second parameter append world string echo "within function \ $number =", $number, ", \ $str", $str, "<br>"; Output parameter} $number = 3; Create an integer as the first parameter $str = "Hello"; Create a string as the second parameter Passbyvalue ($number, $STR); Call echo "function outside \ $number =", $number, ", \ $str", $str, "<br>"; The output calls a value of two parameters?>

The output is:
function inside $number=103, $STR =hello World
$number=3 outside the function, $str =hello
As can be seen, PHP passes parameters by value, and any changes to these values within the function scope are ignored outside the function.

2) pass by reference:

By passing arguments by reference, the memory address of the argument is passed to the formal parameter, and any modification of the parameter within the function affects the arguments because they are stored to the same memory address. When the function returns, the value of the argument changes. The parameters and arguments of the reference pass parameter are all modified for the same block address. If you want a function parameter to be passed through a reference, you need to add a symbol & to the parameter name of the function definition to implement it. Example:

<?php function Passbyvalue (& $number, & $str) {//Pass parameters by reference $number +=100;//The first parameter increases by $STR. = "World"; The second parameter appends the world string echo "function \ $number =", $number, ", \ $str", $str, "<br>"; Output parameter} $number = 3; Create an integer as the first parameter $str = "Hello"; Create a string as the second parameter Passbyvalue ($number, $STR); Call echo "function outside \ $number =", $number, ", \ $str", $str, "<br>"; The output calls a value of two parameters?>

The output is:
function inside $number=103, $STR =hello World
function inside $number=103, $STR =hello World
As can be seen, any changes to these values within a function are reflected in the function as well as in the way the arguments are passed by reference.

3) Default value delivery:

In addition to passing parameters by value and passing parameters by reference, a function can use predefined default parameters. In the case where no parameters are specified, the function uses the default value as the parameter of the function, and the function uses the specified argument in the case of the supplied argument. Example:

<?php function Setfontcolor ($str, $color = "Red") {//Create a parameter with default echo "<font color= '". $color. "". $str. " </font></br> ";} Setfontcolor ("tutorial"); Use the default value of the parameter Setfontcolor ("Hot Goods", "black"); Modify the default value of a parameter?>

Visible, when calling a function, you can pass two arguments, or you can pass a parameter. If only one parameter is passed, the second parameter uses the default value defined when the function is created.
When using PHP's default parameters, it is important to note that the default value must be a constant expression and cannot be a variable. If the function has more than one parameter, you can specify a default value for more than one parameter. However, a parameter with a default value can only be at the end of the parameter list, that is, a parameter with no default value cannot appear to the right of a default value parameter.

4) variable parameter list delivery:

That is, the number of parameters is indeterminate. This approach requires the use of 3 special functions to get the parameters passed in, such as the following table.

Func_num_args () Func_num_args (void) returns the number of arguments passed in a custom function

Func_get_arg () Func_get_arg ($arg _num) gets the value of the $arg_num+1 parameter

Func_get_args () Func_get_args (void) returns an array containing all the arguments

Example: Create a function implementation to sort and output any number of numbers passed at the time of invocation

<?php function Sortnumbers () {//Sort function $count =func_num_args ();//Get the number of arguments actually passed $ary =func_get_args ();//Get an array of all argument lists Rsort ($ary); Sort an array echo "The total number of $count in this order, the results are as follows: \ n"; foreach ($ary as $n) echo "$n"; Output sort after the digital echo "\ n"; } sortnumbers (3, 5, 2, 56, 74, 82, 53, 66, 79, 46); Sort 10 Numbers Sortnumbers (59, 26, 46, 31, 89, 47); Sort 6 digit?>

There are no arguments when creating a function, using the Func_num_args () function inside a function to get the number of arguments that were actually called and saving them to a variable, using the Func_get_args () function to get all the passed arguments, and saving them in an array to the variable.

5. Recursive functions:

A recursive function is the invocation of the function itself in the function body of a function. In the recursive function, the primary function is the function of the tune, and the recursive function calls itself repeatedly, and each call enters a new layer. Example:

<?php function sum ($number)///Recursive functions {if ($number!=0)//Determine whether to stop recursion {return $number +sum ($number-1);//Call this function in return value}} echo "1 00 Summation result: ". SUM (100); Output summation result?>

Recursive functions need only a small number of programs to describe the process of solving the problem of multiple repeated calculations, greatly reducing the code of the program. However, you must set a stop condition for the recursive function, or it will cause a dead loop.

6. Nested functions:

Nested functions are defined as a function in the body of a function, and two functions form a nested relationship. The intrinsic function can only be used when an external function is called. Example:

<?php function Start ()//external functions {echo "is powering on ... \ n"; function boot ()//internal function {echo "Loading bootstrapper ... \ n";} function welcome ($USER)//internal function {echo "Welcome [$user] Use this system. \ n ";}} Start (); Call an external function, at which point the inner function becomes available as boot (); Welcome ("Dwenzhao");?>

The code above defines 3 functions, and Start () is an external function that contains the boot () and welcome () two functions. Therefore, in order to use the boot () and welcome () functions, you must first call the start () function, otherwise you will be prompted that the function is undefined.

7. Determine if the function exists:

When developing large projects, it is often a multi-person collaboration that avoids the need to customize the existence of function names. PHP can use the function_exists () function to determine whether a specified user function already exists. Example:

<?php if (!function_exists ("Userlogin"))//Determine if the Userlogin () function exists {function userlogin ($u)//If it does not exist then create {echo "user $u login succeeded";}} Userlogin ("Dwenzhao"); Call the Userlogin function?>

You can also use the create_function () function to create a temporary function that is dynamically generated by PHP and avoids the same name. Example:

<?php if (!function_exists ("Userlogin"))//Determine if the Userlogin () function exists {function Userlogin ($u)//If not present, create {echo "user $u login Successful";}} $userLogin =create_function (' $u ', ' echo ' user $u login successful "; '); Echo $userLogin ("Dwenzhao"); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.