1. Create a function
The function creation syntax is as follows:
Function func ($ arg_1, $ arg_2,..., $ arg_n)
{
...
}
Any valid PHPCodeYou can define other functions or classes in a function.
In PHP, you do not need to declare a function before calling it. For a function defined in a function, the inner function can be called only after the outer function is called.
<? Phpfunction Foo () {function bar () {echo "I don't exist until Foo () is called. \ n ";}}/* We can't call bar () yet since it doesn' t exist. */Foo ();/* now we can call bar (), Foo ()'s processing has made it accessible. */Bar ();?>
2. Function Parameters
When passing parameters, PHP supports passing by value (default) and by reference. The default parameters and variable length parameters are also supported.
When passing by reference and default parameters, the format is the same as that of C ++, as shown in the following code.
<? PHP/* Passing by reference */function add_some_extra (& $ string) {$ string. = 'and something extra. ';}/* Passing default argument */function makecoffee ($ type = "cappuccino") {return "making a cup of $ type. \ n ";}?>
It should be noted that when passing the default parameter, it must be a constant expression, not a variable, a class member function, or a function. In addition, if multiple parameters need to be passed, the default parameter must be on the right of a non-default parameter.
When using the variable length parameter list, you need to use func_get_args () func_get_arg (), func_arg_num ();
<? PHP // using varargs functionfunction pick ($ A) {$ argc = func_num_args (); For ($ I = 0; $ I <$ argc; $ I ++) {$ Arg = func_get_arg ($ I); If (! Is_null ($ Arg) {return $ Arg ;}} return NULL ;}?>
3. function return value
A function can return any type of value. If no return statement exists, null is returned.
4. function variables
PHP supports calling a function as a string. The following functions perform this operation from a class.
<? Phpclass Foo {function variable () {$ name = 'bar'; $ this-> $ name (); // This callthe bar () method} function bar () {echo "this is bar" ;}}$ Foo = new Foo (); $ funcname = "variable"; $ foo-> $ funcname (); // This CILS $ foo-> variable ()?>
5. Anonymous Functions
It is also called a closure. The following is an anonymous function that uses use to introduce external parameters.
<? Phpfunction gettotal ($ tax, $ products) {$ Total = 0.00; $ func = function ($ quantity, $ product) use ($ tax, & $ total) {$ priceperitem = strtoupper ($ product); $ total + = ($ priceperitem * $ quantity) * ($ tax + 1.0);}; func (products ); return round ($ total, 2) ;}?>