A probe into PHP closure (Closure)

Source: Internet
Author: User
Unknowingly found that PHP has been out of the 5.5 version, and I have been using PHP5.2, let me look like a mountain out of the young man, and land and backward. After I used to use closures in JavaScript, I suddenly became interested in PHP closures.

Thus in the online Wamp integrated development environment, is the PHP5.3 version (PHP5.3 began to introduce the characteristics of closures), I have to say Wamp installation is really convenient to use. Simple configuration, start.

anonymous functions

When it comes to closures, we have to think of anonymous functions, also called closure functions (closures), which seems to be the main implementation of PHP closures. Declaring an anonymous function is this:

$func = function () {    };//with Terminator

As you can see, the anonymous function needs to be returned to a variable if it is to be used because it has no name. Anonymous functions can also declare parameters as normal functions, and call methods are the same:

$func = function ($param) {    echo $param;}; $func (' some string ');//output://some string

By the way, before the introduction of closures, PHP also has a function that can create anonymous functions: Create function, but the code logic can only be written as a string, it seems very obscure and poorly maintained, so very few people use.

Implementing closures

The anonymous function is passed as a parameter in a normal function and can also be returned. This enables a simple closure.

There are three examples below

Example one//defines an anonymous function in a function and calls it function Printstr () {    $func = function ($str) {        echo $str;    };    $func (' some string ');} Printstr ();//Example two//returns the anonymous function in the function and calls it function Getprintstrfunc () {    $func = function ($str) {        echo $str;    };    return $func;} $printStrFunc = Getprintstrfunc (); $printStrFunc (' some string ');//Example three//the anonymous function is passed as an argument and it is called function Callfunc ($func) {    $func (' some string ');} $printStrFunc = function ($str) {    echo $str;}; Callfunc ($printStrFunc);//You can also pass an anonymous function directly. If you know JS, this writing may be familiar callfunc (function ($str) {    echo $str;});

Keywords for connecting closures and external variables: use

Closures can hold some variables and values in the context of the code block. PHP by default, anonymous functions cannot invoke the context variables of the block of code, but need to use the Using keyword.

Let's take another example:

function Getmoney () {    $RMB = 1;    $dollar = 6;    $func = function () use ($RMB) {        echo $rmb;        echo $dollar;    };    $func ();} Getmoney ();//output://1//error, dorllar variable not found

As you can see, dollar is not declared in the Use keyword and is not available in this anonymous function, so be aware of this problem in development.

One might think that it is possible to change the context variable in an anonymous function, but I find that it is not possible:

function Getmoney () {    $RMB = 1;    $func = function () use ($RMB) {        echo $rmb;        Add the value of $RMB to 1        $RMB + +;    };    $func ();    echo $RMB;} Getmoney ();//output://1//1

Ah, the original use of the reference is only a copy of the variable. But I want to fully reference the variable, not copy it.

To achieve this effect, you can actually add a & symbol before the variable:

function Getmoney () {    $RMB = 1;    $func = function () use (& $RMB) {        echo $rmb;        Add the value of $RMB to 1        $RMB + +;    };    $func ();    echo $RMB;} Getmoney ();//output://1//2

OK, so the anonymous function can refer to the variables of the context. If the anonymous function is returned to the outside world, the anonymous function will save the variables referenced by the use, and the outside world will not be able to get those variables, so the concept of a ' closure ' may be clearer.

Change the above example according to the description:

function Getmoneyfunc () {    $RMB = 1;    $func = function () use (& $RMB) {        echo $rmb;        Add the value of $RMB to 1        $RMB + +;    };    return $func;} $getMoney = Getmoneyfunc (); $getMoney (); $getMoney (); $getMoney ();//output://1//2//3

Summarize

The characteristics of the PHP closure is not much surprise, in fact, with class can achieve a similar or even much more powerful function, but also can not be compared with JS closure, can only look forward to PHP after the improvement of the closure support. However, anonymous functions are useful, such as using functions such as preg_replace_callback and so on, without having to declare the callback function externally.

  • 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.