Ahmad Badpey
Ahmad Badpey

Reputation: 6612

access to variables in nested functions in 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?

Upvotes: 3

Views: 3825

Answers (3)

Imal Hasaranga Perera
Imal Hasaranga Perera

Reputation: 10029

According to the Context best way is to pass the variable to the function like this

Sum($b)

But if you are looking for an alternative then you can use closures but REMEMBER PHP<5.3 does not support closures

You can do

$a = 1;
$b = 2;

function test() {
   $b  =   20;
   function Sum() use($b)
   {   
      $b  =   $GLOBALS['a']   +   $b;
  }
}
test();
Sum();
echo $b;

Upvotes: 1

VolkerK
VolkerK

Reputation: 96159

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);

Upvotes: 5

Smamatti
Smamatti

Reputation: 3931

Why not use this?

$a = 1;
$b = 2;

function test(){
    $b = Sum(20);
}

function Sum($value)
{   
    $value = $GLOBALS['a'] + $value;
    return $value;
}

test();
// Sum(); // Why do you need this here??
echo $b;

Edit: Better without globals

$a = 1;
$b = 2;

function Sum($value1, $value2)
{   
    return $value1 + $value2;
}

$b = 20; // you could call Sum($a, 20); instead
$b = Sum($a, $b);
echo $b;

Upvotes: 1

Related Questions