Why is the internal variable of the function referenced externally, not automatically deleted after execution? Function counter ($ d = 0 ){
$ Counter = 1 + $ d;
Return function () use (& $ counter) {return $ counter ++ ;};
}
$ A = counter ();
Echo $ a (); // 1
Echo $ a (); // 2
Problem:
$ A = counter (); // returns the closed function. after the function is executed, all internal variables are deleted;
Ref = 2? Okay, it is equal to 2; delete one; there is also a reference;
The variables in the function are local, and the memory address can be publicly used ??????????
I cannot understand how the memory address of a local variable can be global;
Echo $ a (); // 1
Echo $ a (); // 2
I don't quite understand it. please answer it in detail. I haven't understood it after two hours of research;
----------
Function aaa () {$ a = 1; return function () use (& $ a) {return $ a ++ ;}; // This $ a inherits the $ a memory address of the parent scope;} // The first returned is a closed function: function () use (& $) {return $ a ++;} // function nested function. When an outer function is executed, its internal function becomes global. // closed function: has control of $ a memory; at the same time, it is a global function ...... $ a = aaa (); // after aaa () is executed, the variable is cleared. because & reference, ref_count-1, the memory is not released. echo $ a (); // 1; echo $ a (); // 2;
I am not sure whether the analysis is correct. please correct the information;
Reply to discussion (solution)
What does it mean?
Since you use (& $ counter), of course you need to know the consequences of doing so, because that &, the rules have changed.
Since it is a reference, it means that two or more variables direct to the same data zone and delete one.
JavaScript closures are quite popular, but it seems that few php...
After an anonymous function is assigned to $ a, it is equivalent to the birth of a global function, but this is not the focus...
If $ counter in use is just a copy call, the memory will be released after the value of $ a = $ counter ();
It's just a pointer... so the block exists in this anonymous function and remains
$ Counter in the anonymous function only belongs to $ a. If you make $ B = counter ();, there will be another independent $ counter