Discussion on the problems of PHP closure characteristics in practical application _php Tutorial

Source: Internet
Author: User
Tags php oop
Well, in fact, most of the time it is possible, and some aspects are still very disturbing, the following slow way.
Many languages offer a very elegant and beautiful way to manipulate arrays. In the following example, the closure functionality provided by PHP5.3 and other languages is used to demonstrate how to "objectively" manipulate the iterated group.
The original author compares Mars, I do not know Groovy and the Scala language, so here I add Javascript implementation.
Before you begin, this example is merely an illustration, and does not take into account other factors such as performance.

"Shop Around"

Start with a simple example, with the following arrays:
$nums = Array (10, 20, 30, 40); You need to find the item that is greater than 15 in the array. So, without considering closures, we might write:
$res = Array (), foreach ($nums as $n) {if ($n >) {$res [] = $n;}} If the language itself is supported by closures, it might be written like this (Groovy language)
def res = Nums.findall {it > 15} or using the Scala language
Val res = nums Filter (_ > 15): Javascript 1.6 will be as follows
var res = Nums.filter (function (c) {return c > 15}), because the loop operation has been abstracted, you can see that Groovy, Scala (and Javascript) are beautiful enough to be done in one line.
Of course, if you use PHP5.3 closures, you can also do
$res = Array_filter ($nums, function ($v) {return $v > 15;}); PHP uses more characters than Scala in this respect, but compared to previous examples, it's shorter and better read.

By the way, the above PHP code is actually using LAMBDA parsing, not a real closure, this is not the focus of our current focus. Detailed description of the PHP closure and Lambda analytic type of data, you can refer to here.
It seems to be all right at the moment, so we'll add more difficulty to the topic: find all items greater than 15, then multiply by 2 plus a variable value in the scope to return later.

The implementation of Groovy:
def x = 1def res = nums. findAll {It > *. collect {It * 2 + x}scala implementation:
Val x = 1val res = nums Filter (_ >) Map (_ * 2 + x), Javascript implementation:
var i = 1;var res = nums.filter (function (c) {return c > D}). map (function (c) {return c * 2 + i}); and PHP:
$x = 1; $res = Array_map (function ($v) use ($x) {return $v * 2 + $x;}, Array_filter ($nums, function ($v) {return $v > 15; }); As for the amount of light from the code, it now seems that PHP is different from other languages. First of all, put aside the code of the literal itself of the aesthetic, the above PHP code has an additional problem.
For example, what if you need to use the array's keys instead of values for comparison? Yes, the above code will not be done. At the same time, from a grammatical point of view, the above code is very difficult to read.

Back to basics, you still have to return to old-fashioned ideas to solve the problem:
$x = 1; $res = Array (); foreach ($nums as $n) {if ($n >) {$res [] = $n * 2 + $x;}} Call, it seems clear again. But this time you may be confused: "That is also a blind toss what, this is not the number of operations?" ”。
Yes, the show is still behind. This is the time to let some of the advanced features of PHP come out, to deal with the seemingly self-inflicted "boring problem."

arrayobject– Encapsulation of arrays
PHP has a standard library called SPL, which contains a class called Arrayobject, which provides the ability to manipulate classes like arrays, such as
$res = new Arrayobject (Array (), $res as $v) {echo "$VN";} Arrayobject is a built-in class, so you can encapsulate it like any other class-class operation.

arr-icing on the bag

Now that we have the arrayobject and closures, we can start trying to encapsulate it:
Class ARR extends arrayobject{static function make ($array) {return to New self ($array);} function Map ($func) {$res = new Self (); foreach ($this as $k = + $v) {$res [$k] = $func ($k, $v);} return $res; } function Filter ($func) {$res = new self (), foreach ($this as $k = = $v) {if ($func ($k, $v)) {$res [$k] = $v;}} RET Urn $res; }} OK, everything is ready. The following PHP code can solve the above problem, and it looks syntactically "almost":

$res = Arr::make ($nums)->filter (function ($k, $v) {return $v >)->map (Function ($k, $v) {return $v * 2;} What is the difference between the above code and the traditional way? First, they can be recursively merged to form a chain-of-action call, so you can add more similar operations.

At the same time, the keys of the array can be manipulated by the two parameters of the callback and their items-$k corresponding keys and $v corresponding values. This allows us to use key values in closures, which are not possible in the traditional PHP function Array_fliter.
Another additional benefit is a more consistent API call. Using the traditional PHP function, it is possible that the first parameter is a closure, or a group, or multiple arrays ... Anyway, who knows?
Here is the complete source code for the Arr class, along with other useful functions like reduce and walk, which are actually implemented in a similar way to code.

Game

This is a difficult question to answer-this needs to be determined by the context of the code and by many factors such as the programmer itself. In fact, when I first saw the implementation of the PHP closure, I felt as if I had returned to the Java era that was a long time ago, when I started using anonymous built-in classes (anonymous inner classes) to implement closures. Of course, although this can be done, but it seems to be some superfluous. The PHP closure itself is correct, but its implementation and grammar make me very confused.
Other languages that have closure characteristics can be very convenient to call closures and have elegant syntax at the same time. In the example above, the use of traditional loops in Scala can work, but will you write like this? And from another aspect, then some people say that the above topic using PHP's closure can also be implemented, but generally you will write this?
It can be determined that PHP closures can be a sharp saber in some cases (such as deferred execution and resource invocation), but in the face of traditional iterations and array manipulation. Don't be discouraged, anyway. Writing compatible, refreshing code, and APIs is the most important.

Concluding remarks

Like all the grammatical features that were added later (remember the Java generics feature? And the PHP OOP features of previous years), they all need time to run and eventually stabilize. As PHP5.3 and even future PHP6 become more popular, more and more skills and features are believed to be being excavated by smart programmers in the near future.
Back to the beginning of the first article of the topic, contrast
$res = Arr::make ($nums)->filter (function ($k, $v) {return $v >)->map (Function ($k, $v) {return $v * 2;} ); and
Val res = nums Filter (_ >) Map (_ * 2) The difference between the two. In the final analysis, they are only grammars, which essentially solve the same problem. The application characteristics of programming languages are different, and the nature of the advantages and disadvantages can not be compared.
Finally, here's the code example for this article, and I'm sure you'll find more tips on how to use PHP for functional iterations (not just these).

the experience of the bloggers who are not reliable
Frankly speaking, although the proposed new closures have been known before PHP5.0, but after seeing the closures and LAMBDA functions provided by PHP5.3, there are some discrepancies with what was expected of the original mentality.
Even the closure of the familiar javascript,php in my opinion, like "Other languages have, so I also want to have" the product of this mentality.

But as noted above, PHP differs from other development languages in terms of its own application and philosophy of implementation, as compared to other dynamic languages such as JavaScript.

Therefore, the invocation and implementation of certain features will be different, which will inevitably make people familiar with other similar functions of the language feel uncomfortable.

Since the launch of the PHP5.3, less than half a year, compared to JavaScript and other characteristics such as the closure of the dynamic language, the nature is very immature.

At the same time, the vast number of developers on the PHP5.3 provided by the new features including closures are still on the wait-and-see attitude. The closure of PHP is still present in the laboratory, its application in the actual development, such as to break through not only the language characteristics, but also through the test of efficiency, security and so on.
But believe, as the original author said, with the PHP version of the push, PHP closure applications will be more and more frequent. As PHP4 converted to PHP5, the adaptation to new language features is actually a process of pain and happiness.

http://www.bkjia.com/PHPjc/320720.html www.bkjia.com true http://www.bkjia.com/PHPjc/320720.html techarticle well, in fact, most of the time it is possible, and some aspects are still very disturbing, the following slow way. Many languages offer a very elegant and beautiful way to manipulate arrays ...

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