PHP closure functions: why does a closure have to be an anonymous function?
A lambda or anonymous function is just a function without a name.
eg
$lambda = function($a, $b) { echo $a + $b; };
A closure is a function which has access to variables not specified in its parameter list. In PHP 5.3+ these variables are specified after the use keyword and are linked either by value or by reference at the time the function definition of the closure function is executed.
eg
$foo = 'hello';
$closure = function() use ($foo) { echo $foo; };
$closure();
In JavaScript, all functions are closures in the sense that when functions are nested, there exists a scope chain whereas for instance the innermost function has access to 1. its local variables, 2. the local variables of the function in its enclosing scope known as its closure scope, 3. the local variables of the enclosing scope of the enclosing scope, known as the closure scope of the closure scope, ..., and so on until we can also access N. the global variables which are defined in the topmost scope. Variables declared with var in innermost scopes mask those in outer scopes, otherwise if an innermost variable has the same name as one in an outer scope but is not declared with var then the variable from the outer scope is used.
var zero = 0; // global scope
function f1() {
var one = 1; // third-level closure scope of f4
function f2() {
var two = 2; // second-level closure scope of f4
function f3() {
var three = 3; // first-level closure scope of f4
function f4() {
var four = 4; // local scope of f4
console.log(zero + one + two + three + four);
}
f4();
}
f3();
}
f2();
}
f1();
This is equivalent to the following PHP code:
<?php
$zero = 0; // global scope
$f1 = function() use ($zero) {
$one = 1; // third-level closure scope of f4
$f2 = function() use ($zero, $one) {
$two = 2; // second-level closure scope of f4
$f3 = function() use ($zero, $one, $two) {
$three = 3; // first-level closure scope of f4
$f4 = function() use ($zero, $one, $two, $three) {
$four = 4; // local scope of f4
echo $zero + $one + $two + $three + $four;
};
$f4();
};
$f3();
};
$f2();
};
$f1();
?>
All of this is described here.
So here comes my question. Why do closures in PHP have to be lambda functions? In JavaScript, every function is a closure but does not need to be a lambda function. So why can't we do the following in PHP?:
$foo = 'hello';
function closure() use ($foo) { echo $foo; } // PHP reports a syntax error here
closure();
(Fatal error: syntax error, unexpected T_USE, expecting ';' or '{')
链接地址: http://www.djcxy.com/p/51700.html