Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access to variables in nested functions in php

Tags:

php

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?

like image 273
A.B.Developer Avatar asked May 10 '26 16:05

A.B.Developer


1 Answers

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);
like image 113
VolkerK Avatar answered May 13 '26 05:05

VolkerK