{PHP Function}

Source: Internet
Author: User
Tags type null
Parameters of a user-defined function function return value variable function internal (built-in) function anonymous function one, user-defined function

A function can be defined by the following syntax:

Any valid PHP code is likely to appear inside the function or even include other functions and class definitions.

The function name is the same as the other identifier naming rules in PHP. Valid function names begin with a letter or underscore, followed by letters, numbers, or underscores.

The regular expression can be expressed as: [a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*.

Example #

                           

Example #2 Conditional function (Conditional functions)

                           


Functions in the Example #3 function

                           

All functions and classes in PHP have global scope and can be internally defined externally and vice versa.

PHP does not support function overloading, and it is not possible to cancel the definition or redefine a declared function.

Note: The function name is case-insensitive, but when the function is called, it is usually used in the same form as it was defined.

Note:function only in class can add access rights!

PHP supports variable number of parameters and default parameters. For details, refer to: Func_num_args (), Func_get_arg (), and Func_get_args ().

Example #4 Recursive functions

Recursive functions can be called in PHP. However, avoid recursive function/method calls over 100-200 layers, because the stack can be broken and the current script terminates.

                           

Example #5 callback function

                           


Second, the parameters of the function

The argument list allows you to pass information to a function, which is a comma-delimited list of expressions.

PHP supports passing parameters by value (default), passing parameters by reference, and default parameters. also supports variable number of parameters;

For more information, refer to the variable length parameter list and related function Func_num_args (), Func_get_arg (), and Func_get_args ().

Example #1 passing arrays to functions &

                                        

Output: 1 + 2 = 3

Passing a parameter by reference by default, the function argument is passed by value (so that it does not change the value outside the function even if the value of the parameter is changed inside the function). If you want to allow a function to modify its parameter values, you must pass the arguments by reference.

If you want a parameter of a function to always be passed by reference, you can prepend the symbol & to the argument in the function definition:

Example #2 passing function arguments by reference

                               

The value of the default parameter Example #3 Use default parameters in the function

                                             

echo Makecoffee ( null ),//php also allows array and special type NULL as default parameters, for example: Echo makecoffee ( " espresso " ); @ cappuccino; @ Espresso; ? >

Example #4 Use non-scalar types as default parameters

function Makecoffee ($types = Array ("Cappuccino"), $coffeeMaker = NULL)
{
$device = Is_null ($coffeeMaker)? "Hands": $coffeeMaker;
Return "Making a cup of". Join (",", $types). "With $device. \ n";
}
Echo Makecoffee ();
echo Makecoffee (Array ("Cappuccino", "Lavazza"), "teapot");
?>

The default value must be a constant expression, not an expression such as a variable, a class member, or a function call.

Note that when you use the default parameters, any default parameters must be placed to the right of any non-default parameters, otherwise the function will not work as expected. Consider the following code snippet:

                                    

                                                  

Incorrect usage of function default parameters

                                                    

Example #5 The output of the above example is: warning:missing argument 2 in Call to Makeyogurt () in/usr/local/etc/httpd/htdocs/php3test /functest.html on line 41Making a bowl of raspberry. Example #6 This example output is: Making a bowl of acidophilus raspberry.

Note: From PHP 5, the default value can be passed by reference.

Variable number of parameter lists

PHP 4 and later versions support a variable number of parameter lists in user-defined functions. It's really simple, just use Func_num_args (), Func_get_arg (), and the Func_get_args () function.

mutable parameters do not require special syntax, and parameter lists are still passed to the function as defined by the function and are used in the usual way.

~

Third, return value

The value is returned by using an optional return statement. You can return any type that includes arrays and objects. The return statement immediately aborts the function and returns control back to the line of code that called the function. See return () for more information.

Use of Example #1 return ()

                                        


A function cannot return multiple values, but you can get a similar effect by returning an array.

Example #2 returns an array to get multiple return values

                                        


To return a reference from a function, you must use the reference operator & when the function declares and assigns a return value to a variable:

Example #3 return a reference from a function

                                        


~

~

Four, variable function

PHP supports the concept of mutable functions. This means that if a variable name has parentheses after it, PHP will look for a function with the same name as the value of the variable and try to execute it. Variable functions can be used to implement some purposes, including callback functions, function tables, and so on.

Variable functions cannot be used for language structures such as echo (), print (), unset (), Isset (), empty (), include (), require (), and similar statements. These structures need to be used as variable functions using their own wrapper functions.

Example #1 Variable Function example

                               

\ n ";} function bar ($arg = ') {echo ' in bar (); Argument was ' $arg '.
\ n ";} Use Echo's wrapper function Echoit ($string) {echo $string;} $func = ' foo '; $func (); This calls foo () $func = ' bar '; $func (' Test '); This calls bar () $func = ' Echoit '; $func (' Test '); This calls Echoit ()?>

You can also use the properties of a mutable function to invoke a method of an object.

Example #2 Variable Method Example

                               

$name (); This calls the bar () method} function Bar () {echo ' This is Bar ';}} $foo = new Foo (); $funcname = "Variable"; $foo-$funcname (); This calls $foo->variable ()?>

See Call_user_func (), mutable variables, and function_exists ().

~

V. Internal (built-in) functions

PHP has a number of standard functions and structures. There are also functions that need to be compiled with specific PHP extensions, or you will get a fatal "undefined function" error when using them. For example, to use the image function like Imagecreatetruecolor (), you need to add GD support when compiling PHP. Or, to use the mysql_connect () function, you need to add MySQL support when compiling PHP. There are many core functions that have been included in each version of PHP, such as string and variable functions. Call Phpinfo () or get_loaded_extensions () to know that PHP has loaded those extension libraries. It should also be noted that many extension libraries are valid by default. The PHP manual organizes their documents according to different extensions. Refer to the configuration, installation, and respective extensions section for information on how to set up PHP.

How to read the function prototype in the manual explains how to read and understand the prototype of a function. It is important to confirm what a function will return, or whether the function directly acts on the passed parameter. For example, the Str_replace () function returns a modified string, while Usort () directly acts on the passed parameter variable itself. In the manual, each function page has information about function parameters, behavior changes, the return value of success or not, and the conditions of use. Understanding these important (often subtle) differences is key to writing the correct PHP code.

Note: If the argument type passed to the function is inconsistent with the actual type, such as passing an array to a variable of type string, the return value of the function is indeterminate. In this case, the function usually returns NULL. But this is only an agreement, and it is not necessarily the case.

See function_exists (), function Reference, Get_extension_funcs (), and DL ().

Vi. anonymous function Note: The anonymous function is only valid in PHP 5.3.0 and above.

The anonymous function (Anonymous functions), also called the closure function (closures), allows temporary creation of a function without a specified name. The most frequently used parameter for a callback function (callback). Of course, there are other applications as well.

Example #1 Anonymous Function Example

echo Preg_replace_callback (' ~-([A-z]) ~ ', function ($match) {
return Strtoupper ($match [1]);
}, ' Hello-world ');
Output HelloWorld
?>

The closure function can also be used as the value of a variable. PHP automatically converts an expression into an object instance of the built-in class closure. Assigning a closure object to a variable is the same as the syntax for assigning a value to a normal variable, and a semicolon is the last thing to add.

Example #2 anonymous function variable Assignment example

$greet = function ($name)
{
printf ("Hello%s\r\n", $name);
};

$greet (' World ');
$greet (' PHP ');
?>

The closure object also inherits class properties from the parent scope. These variables must be declared on the head of a function or class. Inheriting a variable from a parent scope differs from using a global variable *. Global variables exist in a global scope, regardless of which function is currently executing. The parent class scope of closure is the function that declares the closure (not necessarily the function it is called). Examples are as follows:

Example #3 Closures and scopes

A basic shopping cart, including some already added items and the quantity of each item.
There is one way to calculate the total price of all the items in the shopping cart. The method uses a closure as the callback function.
Class Cart
{
Const Price_butter = 1.00;
Const PRICE_MILK = 3.00;
Const PRICE_EGGS = 6.95;

Protected $products = Array ();

Public function Add ($product, $quantity)
{
$this->products[$product] = $quantity;
}

Public Function getquantity ($product)
{
return Isset ($this->products[$product])? $this->products[$product]:
FALSE;
}

Public Function Gettotal ($tax)
{
$total = 0.00;

$callback =
function ($quantity, $product) use ($tax, & $total)
{
$pricePerItem = constant (__class__. "::P rice_".
Strtoupper ($product));
$total + = ($pricePerItem * $quantity) * ($tax + 1.0);
};

Array_walk ($this->products, $callback);
Return round ($total, 2);;
}
}

$my _cart = new cart;

Add items to your shopping cart
$my _cart->add (' Butter ', 1);
$my _cart->add (' Milk ', 3);
$my _cart->add (' eggs ', 6);

Hit the total price, which has a sales tax of 5%.
Print $my _cart->gettotal (0.05). "\ n";
The result is 54.29
?>

Anonymous functions are now implemented through the closure class. It is currently unstable and does not apply to formal development.

Note: The anonymous function is only valid in PHP 5.3.0 and above.

Note: Within closure, you can call Func_num_args (), Func_get_arg (), and Func_get_args () functions to get parameter information.

~

~

  • Related Article

    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.