javascript - PHP closure functions: why does a closure have to be an anonymous function? -



javascript - PHP closure functions: why does a closure have to be an anonymous function? -

a lambda or anonymous function function without name.

e.g.

$lambda = function($a, $b) { echo $a + $b; };

a closure function has access variables not specified in parameter list. in php 5.3+ these variables specified after utilize keyword , linked either value or reference @ time function definition of closure function executed.

e.g.

$foo = 'hello'; $closure = function() utilize ($foo) { echo $foo; }; $closure();

in javascript, functions closures in sense when functions nested, there exists scope chain whereas instance innermost function has access 1. local variables, 2. local variables of function in enclosing scope known closure scope, 3. local variables of enclosing scope of enclosing scope, known closure scope of closure scope, ..., , on until can access n. global variables defined in topmost scope. variables declared var in innermost scopes mask in outer scopes, otherwise if innermost variable has same name 1 in outer scope not declared var variable outer scope used.

var 0 = 0; // global scope function f1() { var 1 = 1; // third-level closure scope of f4 function f2() { var 2 = 2; // second-level closure scope of f4 function f3() { var 3 = 3; // first-level closure scope of f4 function f4() { var 4 = 4; // local scope of f4 console.log(zero + 1 + 2 + 3 + four); } f4(); } f3(); } f2(); } f1();

this equivalent next php code:

<?php $zero = 0; // global scope $f1 = function() utilize ($zero) { $one = 1; // third-level closure scope of f4 $f2 = function() utilize ($zero, $one) { $two = 2; // second-level closure scope of f4 $f3 = function() utilize ($zero, $one, $two) { $three = 3; // first-level closure scope of f4 $f4 = function() utilize ($zero, $one, $two, $three) { $four = 4; // local scope of f4 echo $zero + $one + $two + $three + $four; }; $f4(); }; $f3(); }; $f2(); }; $f1(); ?>

all of described here.

so here comes question. why closures in php have lambda functions? in javascript, every function closure not need lambda function. why can't next in php?:

$foo = 'hello'; function closure() utilize ($foo) { echo $foo; } // php reports syntax error here closure();

(fatal error: syntax error, unexpected t_use, expecting ';' or '{')

javascript php closures lexical-closures php-closures

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -