suppose i have two nested function like this :
$a = 1;
$b = 2;
function test(){
$b = 20;
function Sum()
{
$b = $GLOBALS['a'] + $b;
}
}
test();
Sum();
echo $b;
now i want in function Sum() access to $b variable declared in function test();
How do you do?
Wild-Guessing-mode:
Your function Sum() would "normaly" take two parameters/operands like
function Sum($a, $b) {
return $a+$b;
}
echo Sum(1, 20);
Now you have the function Test() and you want it to return a function fn that takes only one parameter and then calls Sum($a, $b) with one "pre-defined" parameter and the one passed to fn.
That's called either currying or partial application (depending on what exactly you implement) and you can do something like that with lambda functions/closures since php 5.3
<?php
function Sum($a, $b) {
return $a + $b;
}
function foo($a) {
return function($b) use ($a) {
return Sum($a, $b);
};
}
$fn = foo(1) // -> Sum(1, $b);
$fn = foo(2) // -> Sum(2, $b);
echo $fn(47);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With