Functions for learning PHP at the front end and functions for learning PHP

Source: Internet
Author: User

Functions for learning PHP at the front end and functions for learning PHP
* Directory [1] Function Definition [2] function parameters [3] return values [4] variable functions [5] callback functions [6] recursive functions [7] Loading functions [8] Anonymous before the Function

The real power of PHP comes from its functions: it has over 1000 built-in functions. This article will introduce php functions in detail

[Note] the detailed content of javascript Functions is now

 

Function Definition

In addition to built-in PHP functions, you can create your own functions. A function is a statement block that can be reused in a program. The function is not executed immediately when the page is loaded. The function is executed only when it is called.

The User-Defined function Declaration starts with the keyword "function". The function name is the same as the naming rules for other identifiers in PHP. A valid function name must start with a letter or underline followed by a letter, number, or underline.

Function functionName () {code executed ;}
<? Phpfunction writeMsg () {echo "Hello world! ";} WriteMsg (); // call a function?>

 

Function Parameters

You can pass information to the function through parameters, which are similar to variables. The parameter is defined in brackets after the function name. You can add any number of parameters separated by commas (,).

<?phpfunction familyName($fname) {  echo "$fname Zhang.<br>";}familyName("Li");familyName("Hong");familyName("Tao");familyName("Xiao Mei");familyName("Jian");?>

Reference Transfer

By default, function parameters are passed through values. 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 be passed through reference, you can add a symbol before this parameter in the function definition &

<?phpfunction add_some_extra(&$string){    $string .= 'and something extra.';}$str = 'This is a string, ';add_some_extra($str);echo $str;    // outputs 'This is a string, and something extra.'?>

Default parameters

A function can define the default value of a scalar parameter in the C ++ style.

<? Phpfunction setHeight ($ minheight = 50) {echo "The height is: $ minheight <br>" ;}setheight (350); setHeight (); // The default value is 50 setHeight (135); setHeight (80);?>

PHP also allows the use of array and special type NULL as the default parameter

<?phpfunction 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");?>

[Note] 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

Variable parameters

[Func_get_args ()]

Func_get_args () is equivalent to the arguments in the javascript function, and stores real parameters as arrays.

function demo(){    $arr = func_get_args();    $sum = 0;    for($i = 0; $i<count($arr); $i++){        $sum += $arr[$i];    }    return $sum;}//45echo demo(1,2,3,4,5,6,7,8,9);

In addition, there are two common functions: func_num_args () and func_get_arg ()

Total number of parameters returned by the func_num_args () function

The func_get_arg () function receives a number parameter and returns the specified parameter.

Function more_args () {for ($ I = 0; $ I <func_num_args (); $ I ++) {echo "th ". $ I. "parameter ". func_get_arg ($ I ). "<br>" ;}} more_args ("one", "two", "three", 1, 2, 3 );

 

Return Value

To return a function value, use the return statement. If return is omitted, the return value is NULL.

<?phpfunction sum($x,$y) {  $z=$x+$y;  return $z;}echo "5 + 10 = " . sum(5,10) . "<br>";echo "7 + 13 = " . sum(7,13) . "<br>";echo "2 + 4 = " . sum(2,4);?>

 

Variable Functions

Variable functions are also called variable functions. If a variable name has parentheses, PHP searches for a function with the same name as the variable value and tries to execute it. Variable functions can be used for some purposes, including callback functions and function tables.

[Note] variable functions cannot be used for echo, print, unset (), isset (), empty (), include, require, and similar language structures. You need to use your own packaging functions to use these structures as variable functions.

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

 

Callback Function

A callback function uploads a function name as a parameter to another function. This function is called a callback function.

function demo($num,$n){    for($i=0;$i<$num;$i++){        if($n($i)){            echo $i.'<br>';        }    }}function test($i){    if($i%5){        return true;    }}demo(20,'test');

Call_user_func_array

Call_user_func_array can be used to call the callback function, and an array parameter is used as the callback function parameter.

mixed call_user_func_array ( callable $callback , array $param_arr )

Call the first parameter as the callback function, and input the parameter array as the parameter (param_arr) of the callback function.

function demo($num,$n){    for($i=0;$i<$num;$i++){        if(call_user_func_array($n,array($i))){            echo $i.'<br>';        }    }}function test($i){    if($i%5){        return true;    }}demo(20,'test');

The call_user_func_array () function is usually used to implement the callback function, instead of the variable function, because the variable function cannot pass the methods in the object or static methods in the class.

function demo($num, $n) {    for($i=0; $i<$num; $i++) {        if(call_user_func_array($n, array($i))){            echo $i."<br>";        }        }}    class Filter {    function one($i) {        if($i%3==0) {            return true;        }    }    static function two($i) {        if(preg_match('/3/', $i)) {            return true;        }    }}demo(500, array(new Filter(), "one"));demo(500, array("Filter", "two"));

 

Recursive functions

Calling a function is a recursive function.

<?php    function test( $n ) {                    echo $n;         if($n>0){            test($n-1);                           }           echo $n;     }    test(5);//543210012345?>

 

Load function library

Use the include () function to introduce external files

test.phpfunction one(){    echo '111';}<?phpinclude ('test.php');one();//111?>

However, if you accidentally introduce the function multiple times so that the function is redefined and the variable is assigned a value again, it will cause an error.

test.phpfunction one(){    echo '111';}<?phpinclude ('test.php');include ('test.php');one();//111?>

In this case, use the include_once () function to ensure that the same file is introduced only once.

test.phpfunction one(){    echo '111';}<?phpinclude_once('test.php');include_once('test.php');one();//111?>

Require ()

You can also use require () to introduce external files (). Include () and require () are almost equivalent. The difference is that include in script execution. When processing fails, include () generates a warning while require () leads to a fatal error.

[Note] require_once () and include () _ once are similar.

 

Anonymous Functions

An Anonymous function (Anonymous functions), also called a closure function (closures), allows you to temporarily create a function without a specified name. The value that is most often used as the callback function parameter

In fact, php anonymous functions are similar to functional expressions in javascript.

[Note] the anonymous function must end with a plus sign. Otherwise, an error is returned.

<?php$greet = function($name){    printf("Hello %s\r\n", $name);};$greet('World');$greet('PHP');?>

Closure

PHP closure implementation mainly relies on anonymous Functions

Passing in an anonymous function as a parameter in a common function can also be returned. This implements a simple closure.

Closure has two features:

1. As a reference to a function variable-when a function is returned, it is activated.

2. A closure is a stack that does not release resources when a function returns.

In fact, the above two points can be merged, that is, when the closure function returns, the internal variables of the function are activated, and the stack zone of the function is retained.

The closure can inherit variables from the parent scope. Any such variables should be passed in the use language structure.

$message = 'hello';$example = function () use ($message) {    var_dump($message);};echo $example();//string 'hello' (length=5)

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.