JavaScript:
function calc(x) {
return function(y) {
return x + y;
};
}
console.log(calc(1)(2));
This will return 3
.
I tried the same with PHP:
function calc($x) {
return function($y) {
return $x + $y;
};
}
echo calc(1)(2);
This will return 2
. And I get an E_NOTICE:
E_NOTICE : type 8 -- Undefined variable: x -- at line 4
Why is the variable x
undefined? Is it because that wouldn't work with PHP or am I doing something wrong?
</div>
it's called a closure :
http://php.net/manual/en/class.closure.php
http://php.net/manual/en/functions.anonymous.php
function calc($x) {
return function($y) use($x){
return $x + $y;
};
}