{Php function}

Source: Internet
Author: User
{Php function} user-defined function parameter return value variable internal (built-in) function anonymous function 1 user-defined function

A function can be defined by the following syntax:

Any valid PHP code may appear inside the function, or even include other functions and class definitions.

The name of the function is the same as that of other identifiers in PHP. A valid function name must start with a letter or underline followed by a letter, number, or underline.

[A-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ x7f-\ xff] *.

Example #

                           

Example #2 Conditional functions)

                           


Example #3 functions

                           

All functions and classes in PHP have a global scope. external calls can be defined internally, and vice versa.

PHP does not support function overloading, and it is impossible to cancel or redefine declared functions.

Note: the function name is case-insensitive. However, when calling a function, it is usually defined in the same format.

Note: The function can only be accessed in the class!

PHP supports variable parameters and default parameters. For details, see func_num_args (), func_get_arg (), and func_get_args ().

Example #4 recursive functions

You can call recursive functions in PHP. However, avoid calling recursive functions/methods that exceed layer 100-layer 200, because the stack may be broken to terminate the current script.

                           

Example #5 callback function

                           


II. function parameters

You can pass information to the function through the parameter list, that is, the list of expressions that use commas as separators.

PHP supports passing parameters by value (default), passing parameters by reference, and default parameters. Variable parameters are also supported;

For more information, see the variable length parameter list and related functions func_num_args (), func_get_arg (), and func_get_args ().

Example #1 pass an array to a function &

                                        

Output: 1 + 2 = 3

By default, a function parameter is passed through a reference parameter (so it does not change the value outside the function even if the parameter value is changed inside the function ). If you want to allow a function to modify its parameter values, you must pass parameters through reference.

If you want a function parameter to always pass through the reference, you can add a symbol before the parameter in the function definition &:

Example #2 pass function parameters with reference

                               

Default parameter value Example #3 use the default parameter in the function

                                             

Echo makecoffee (null); // PHP also allows the use of arrays and special types of NULL as default parameters, such as: echo makecoffee ("espresso"); // @ cappuccino ;@; @ espresso;?>

Example #4 use the non-standard type as the default parameter

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. it cannot be a variable, a class member, or a function call.

Note that when using the default parameter, any default parameter must be placed on the right of any non-default parameter; otherwise, the function will not work as expected. Consider the following code snippet:

                                    

                                                  

Incorrect default function parameter usage

                                                    

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 41 Making a bowl of raspberry. example #6 The output of this example is: Making a bowl of acidophilus raspberry.

Note: Since PHP 5, the default value can be passed through reference.

Variable parameter list

PHP 4 and later versions support variable parameter lists in user-defined functions. In fact, it is very simple. you only need to use the func_num_args (), func_get_arg (), and func_get_args () functions.

Variable parameters do not require special syntax. the parameter list is still passed to the function as defined by the function, and these parameters are used as usual.

~

III. return values

Value is returned by using an optional return statement. Returns any types including arrays and objects. The return statement immediately terminates the function and returns the control to the code line that calls the function. For more information, see return ().

Use of Example #1 return ()

                                        


The function cannot return multiple values, but you can return an array to obtain similar results.

Example #2 return an array to obtain multiple return values

                                        


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

Example #3 return a reference from the function

                                        


~

~

IV. variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses, 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 for some purposes, including callback functions and function tables.

Variable functions cannot be used in language structures, such as echo (), print (), unset (), isset (), empty (), include (), require (), and similar statements. You need to use your own packaging functions to use these structures as variable functions.

Example #1 variable function Example

                               

\ N ";} function bar ($ arg ='') {echo "In bar (); argument was '$ arg '.
\ N ";}// use the echo packaging function echoit ($ string) {echo $ string ;}$ func = 'foo'; $ func (); // This callfoo () $ func = 'bar'; $ func ('test'); // This callbar () $ func = 'echoit '; $ func ('test'); // This callechoit ()?>

You can also call an object method by using the features of a variable function.

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 (), Variable variables, and function_exists ().

~

5. internal (built-in) functions

PHP has many standard functions and structures. Some other functions need to be compiled with the PHP extension module in particular. Otherwise, a fatal "undefined function" error will be generated when you use them. For example, to use the image function, such as imagecreatetruecolor (), add GD support when compiling PHP. Alternatively, to use the mysql_connect () function, you must add MySQL support when compiling PHP. Many core functions are included in each version of PHP, such as strings and variable functions. Call phpinfo () or get_loaded_extensions () to find out which extension libraries PHP has loaded. Note that many extension libraries are valid by default. The PHP manual organizes their documents according to different extension libraries. For more information about how to set up PHP, see configuration, installation, and their extension libraries.

The manual explains how to read the function prototype and 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 the modified string, while the usort () function directly acts on the passed parameter variable itself. In the manual, each function page contains information about function parameters, returned values of behavior changes, success or failure, and usage conditions. Understanding these important (often subtle) differences is the key to writing correct PHP code.

Note: If the parameter type passed to the function is different from the actual type, for example, if an array is passed to a string type variable, the return value of the function is uncertain. In this case, the function usually returns NULL. But this is just an agreement, not necessarily.

For more information, see function_exists (). For Function Reference, get_extension_funcs () and dl ().

VI. Anonymous function Note: Anonymous functions are only available in PHP 5.3.0 and later versions.

An Anonymous function (Anonymous functions), also called a closure function (closures), allows you to temporarily create a function without a specified name. It is most often used as a callback function parameter. Of course, there are other applications.

Example #1 Anonymous function Example

Echo preg_replace_callback ('~ -([A-z]) ~ ', Function ($ match ){
Return strtoupper ($ match [1]);
}, 'Hello-world ');
// Output helloWorld
?>

Closure functions can also be used as variable values. PHP automatically converts the expression to an object instance with built-in Closure class. The method for assigning a closure object to a variable is the same as the syntax for assigning a value to a common variable. a semicolon should also be added.

Example #2 Example of an anonymous function variable assignment

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

$ Greet ('world ');
$ Greet ('php ');
?>

Closure objects also inherit class attributes from the parent scope. These variables must be declared in the function or class header. Inheriting variables from the parent scope is * different from using global variables. Global variables exist in a global range, regardless of the function currently being executed. Closure's parent class scope is to declare the closure function (not necessarily the function it is called ). Example:

Example #3 Closures and scope

// A basic shopping cart, including some added items and the quantity of each item.
// One method is used to calculate the total price of all items in the shopping cart. This method uses closure as the callback function.
Class Cart
{
Const price_butter= 1.00;
Constprice_milk = 3.00;
Const maid = 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 _. ": PRICE _".
Strtoupper ($ product ));
$ Total + = ($ pricePerItem * $ quantity) * ($ tax + 1.0 );
};

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

$ My_cart = new Cart;

// Add entries to the shopping cart
$ My_cart-> add ('butter ', 1 );
$ My_cart-> add ('milk', 3 );
$ My_cart-> add ('eggs', 6 );

// Calculate the total price, with a sales tax of 5%.
Print $ my_cart-> getTotal (0.05). "\ n ";
// The result is 54.29
?>

Currently, anonymous functions are implemented through the Closure class. It is not stable yet and does not apply to formal development.

Note: Anonymous functions are only available in PHP 5.3.0 and later versions.

Note: within closure, you can call functions such as func_num_args (), func_get_arg (), and func_get_args () to obtain parameter information.

~

~

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.