The closure in PHP is detailed

Source: Internet
Author: User
Tags aliases oscommerce

PHP Closure (Closure) using the detailed

Font: [Increase decrease] Type: Reprint time: 2013-05-02 I want to comment

This article describes the use of PHP closures (Closure), the need for a friend reference under

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:

Copy CodeThe code is as follows:
$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:
Copy CodeThe code is as follows:
$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

Copy CodeThe code is as follows:
Example One
Define an anonymous function in the function and call 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
Pass an anonymous function as a parameter and call it
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:

Copy CodeThe code is as follows:
function Getmoney () {
$RMB = 1;
$dollar = 6;
$func = function () use ($RMB) {
Echo $RMB;
Echo $dollar;
};
$func ();
}

Getmoney ();

Output:
1
Error, unable to find dorllar variable


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:

Copy CodeThe code is as follows:
function Getmoney () {
$RMB = 1;
$func = function () use ($RMB) {
Echo $RMB;
Add 1 to the $RMB value.
$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:

Copy CodeThe code is as follows:
function Getmoney () {
$RMB = 1;
$func = function () use (& $RMB) {
Echo $RMB;
Add 1 to the $RMB value.
$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:

Copy CodeThe code is as follows:
function Getmoneyfunc () {
$RMB = 1;
$func = function () use (& $RMB) {
Echo $RMB;
Add 1 to the $RMB value.
$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.

Many open source systems, such as the oscommerce framework, will find the use of this keyword in their source code, such as the oscommerce framework in the index.php file appears in the source code:

Use Oscommerce\om\core\autoloader;use oscommerce\om\core\oscom;

In fact, PHP's use keyword was introduced from the php5.3 version above. Its role is to alias an external reference. This is an important feature of the namespace, which is similar to creating a connection flag for a file or directory on a UNIX-based file system.

The PHP namespace supports three aliases (or references):

1. Take an alias for a class

2. Take an alias for an interface

3. Take an alias for a namespace

All three of these methods are done using the USE keyword. The following are examples of three aliases:
Example #1 importing/aliasing with the use operator

<?phpnamespacefoo;usemy\full\classnameasanother;//thisisthesameasusemy\full\nsnameasnsnameusemy\full\nsname ;//importingaglobalclassusearrayobject; $obj =newnamespace\another;//instantiatesobjectofclassfoo\another$obj= Newanother;//instantiatesobjectofclassmy\full\classnamensname\subns\func ();//callsfunctionmy\full\nsname\subns \func$a=newarrayobject (Array (1));//instantiatesobjectofclassarrayobject//withoutthe "Usearrayobject" Wewouldinstantiateanobjectofclassfoo\arrayobject?>

Note that, for named names, the full name contains delimiters, such as Foo\bar, but not foobar, and "\foo\bar" the head of the "\" is not necessary, and it is not recommended to write. The introduction name must be a full name, and there is no program association with the current namespace.

PHP can also declare multiple on the same line, equivalent to the above wording

<?phpuseMy\Full\ClassnameasAnother,My\Full\NSname; $obj =newanother;//instantiatesobjectofclassmy\full\ Classnamensname\subns\func ();//callsfunctionmy\full\nsname\subns\func?>

It is also worth saying that the introduction is performed at compile time, so aliases do not affect dynamic classes, for example:

<?phpuseMy\Full\ClassnameasAnother,My\Full\NSname; $obj =newanother;//instantiatesobjectofclassmy\full\ classname$a = ' another '; $obj = New $a; Instantiates object of Class another?>

This is because the variable $ A is assigned a ' another ', and when compiled, a $ A is positioned to Classname.

For more detailed usage, readers can check the PHP manual or follow the related articles on this site.

How to use closure class in PHP and its explanation

Submission: MRR font: [Increase decrease] Type: Reprint time: 2015-10-09 I want to comment

The closure class is also called anonymous function, which is introduced in php5.3. As the name implies, anonymous functions are functions that do not have names defined. This article introduces you to the use of PHP closure class and detailed, the need for friends can refer to the following

Closure, an anonymous function, also known as anonymous functions, was introduced when php5.3. anonymous functions are functions that do not have a name defined . This is a very memorable understanding of the definition of anonymous functions.

The Closure class (PHP 5 >= 5.3.0) is an introduction to classes that represent anonymous functions. Anonymous functions (introduced in PHP 5.3) produce this type of object, let's take a look at the use and introduction of the PHP closure class.

The PHP closure class was previously introduced in the PHP pre-defined interface, but it is not interface Oh, it is an internal final class. The closure class is used to represent anonymous functions, and all anonymous functions are instances of the closure class.

$func = function () {  echo ' func called ';}; Var_dump ($func); Class Closure#1 (0) {} $reflect =new reflectionclass (' Closure '); Var_dump (  $reflect->isinterface (),//false  $reflect->isfinal (),//true  $reflect->isinternal ()//true);

The closure class structure is as follows:

closure::__construct-Constructors for prohibiting instantiation
closure::bind-copy a closure that binds the specified $this object and class scope.
closure::bindto-Copy the current closure object, binding the specified $this object and the class scope.

See an example of binding $this objects and scopes:

Class lang{  private $name = ' php ';} $closure = function () {  return $this->name;}; $bind _closure = Closure::bind ($closure, New Lang (), ' Lang '), Echo $bind _closure (); Php

In addition, PHP uses the Magic Method __invoke () to turn the class into a closure:

Class Invoker {public  function __invoke () {return __method__;}} $obj = new Invoker;echo $obj (); Invoker::__invoke


PHP's Closure (Closure) anonymous function

Submission: Hebedich font: [Increase decrease] Type: Reprint time: 2015-02-22 I want to comment

This article mainly introduces the PHP anonymous function introduced by php5.3, that is, the closure (Closure), and the role of closures, very detailed, recommended to the needs of small partners.

PHP's Closure (Closure) is an anonymous function, introduced by PHP5.3.

The syntax of a closure is simple, and the key word to note is that only use,use are connected to closures and external variables.

Copy CodeThe code is as follows:
$a = function () use ($b) {}

A simple example is as follows:

Copy CodeThe code is as follows:
function callback ($fun) {
$fun ();
}
$msg = "Hello, everyone";
$fun = function () use ($msg) {
Print "This is a closure with string value, MSG is: $msg. <br/>/n";
};
$msg = "Hello, everybody";
Callback ($fun);

The result: This is a closure use string value, msg Is:hello, everyone. <BR/>/n

In the new open closure syntax for PHP, we used use to define variables outside the closure. Here we use the external variable $msg, after the definition, and then the value of the change, the closure is executed after the output is the original value. The value of the closure use is determined when the closure is created by the underlying type parameter passed as a pass-through value.

Small applications are as follows:

Copy CodeThe code is as follows:
/**
* A counter generator that uses closures
* This is actually a reference to Python in the introduction of closures when the example ...
* We can consider this:
* 1. Each time the counter function is called, a local variable $counter is created, initialized to 1.
* 2. Then a closure is created, and the closure produces a reference to the local variable $counter.
* 3. The function counter returns the created closure and destroys the local variable, but at this point there is a reference to the $counter by the closure.
* It's not going to be recycled, so we can understand that the closure, returned by the function counter, carries a free State
Variable.
* 4. Since each call to counter creates separate $counter and closures, the returned closures are independent of each other.
* 5. Executes the returned closure, and the Free State variable it carries is self-incremented and returned, resulting in a counter.
* Conclusion: This function can be used to generate counters that are independent of each other.
*/
function counter () {
$counter = 1;
return function () use (& $counter) {return $counter + +;};
}
$counter 1 = counter ();
$counter 2 = counter ();
echo "Counter1:". $counter 1 (). "<br/>/n";
echo "Counter1:". $counter 1 (). "<br/>/n";
echo "Counter1:". $counter 1 (). "<br/>/n";
echo "Counter1:". $counter 1 (). "<br/>/n";
echo "Counter2:". $counter 2 (). "<br/>/n";
echo "Counter2:". $counter 2 (). "<br/>/n";
echo "Counter2:". $counter 2 (). "<br/>/n";
echo "Counter2:". $counter 2 (). "<br/>/n";
?>

The role of closures

1. Reduce the code of the Foreach Loop
such as the example cart in the Handbook http://php.net/manual/en/functions.anonymous.php

Copy CodeThe code is as follows:
<?php
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);
};
Use a user-defined function to do callback processing for each element in the array
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
?>

Here, if we transform the Gettotal function, we must use foreach.

2. Reduce the parameters of the function

Copy CodeThe code is as follows:
function html ($code, $id = "", $class = "") {
if ($id!== "") $id = "id = \" $id \ "";
$class = ($class!== "")? "class =\" $class \ ">": ">";
$open = "< $code $id$class";
$close = "</$code >";
return function ($inner = "") Use ($open, $close) {
Return "$open $inner$close";
};
}

If you use the usual method, we will put inner into the HTML function parameters, so that neither code reading nor use is as good as using closures.

3. Lifting the recursive function

Copy CodeThe code is as follows:
<?php
$fib = function ($n) use (& $fib) {
if ($n = = 0 | | $n = = 1) return 1;
Return $fib ($n-1) + $FIB ($n-2);
};
Echo $fib (2). "\ n"; 2
$lie = $FIB;
$fib = function () {die (' error ');};/ /rewrite $FIB Variable
Echo $lie (5); Error because $FIB is referenced by closure

Note that the use of the & in the above topic is used, and the error fib (n-1) is not found in this case (the type of FIB is not defined previously).

So when you want to use closures to remove the loop function, you need to use the

Copy CodeThe code is as follows:
<?php
$recursive = function () use (& $recursive) {
The function is now available as $recursive
}

Such a form.

4. Delay Binding

If you need to delay the binding of a variable inside a use, you need a reference, or you will make a copy of it when you define it.

Copy CodeThe code is as follows:
<?php
$result = 0;
$one = function ()
{
Var_dump ($result);
};
$two = function () use ($result)
{
Var_dump ($result);
};
$three = function () use (& $result)
{
Var_dump ($result);
};
$result + +;
$one (); Outputs NULL: $result is not in scope
$two (); outputs int (0): $result was copied
$three (); outputs int (1)

The use of references and non-use of references represents the assignment of a call, or the assignment of a value at the time of declaration

Small partners on the anonymous function of PHP is the closure function has a new understanding of it, I hope this article can give you some hints, I hope you can like.

The closure in PHP is detailed

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.