How can we easily explain the following application examples of closures and closures in a specific project? In php, does {code...} play a similar role as below? {Code...} is generally used under what circumstances in a specific project? Can you give a small example of how to explain the following closure and closure application examples in a specific project?
Php,
function demo(){ $a=10; $b=20; $fun=function() use ($a,$b){ echo $a+$b; };}demo();
Is it similar to the following?
class cls{ public $a=10; public $b=20; public function fun(){ echo $this->a+$this->b; }}$obj=new cls;$obj->fun();
Under what circumstances will I use in a specific project? Can you give a small example?
Reply content:
How can we easily explain the following application examples of closures and closures in a specific project?
Php,
function demo(){ $a=10; $b=20; $fun=function() use ($a,$b){ echo $a+$b; };}demo();
Is it similar to the following?
class cls{ public $a=10; public $b=20; public function fun(){ echo $this->a+$this->b; }}$obj=new cls;$obj->fun();
Under what circumstances will I use in a specific project? Can you give a small example?
Change public to private.
Closure is a concept in functional programming. With the development of computer languages towards functional programming languages, many languages start to support anonymous functions (and lamada expressions) and packages. The use of anonymous functions is very large. Closures exist to support lamada expressions.
However, in languages such as Java, you can write the original code for the habit of using classes. Here I think using closures can reduce the amount of code!
A few days ago, I wrote a draft about closures
Https://segmentfault.com/q/1010000004736461
Object-oriented function objects include function scope transfer. Closures can be understood literally as closed scope package transfer. After a common function is returned, the function scope (function stack memory) disappears. When a function is called, the function scope (function space is imported into the stack) is generated ). While the closure generation function disappears its own scope when it returns, it also produces a new scope. The new scope does not go into the stack, resulting in a hierarchical relationship between the stack and the level. For example, if a (common) function calls the B (generated by the closure) function, B returns the c (closure) function. The bottom of the function stack is the scope of a. The top is the scope of B, and function B returns, B has only a left in the outbound stack, and the generated c function scope is passed to scope a. In this case, scope a contains scope c, and scope c inherits (replicates) from scope B, it is like B's scope is not extinct.