Senica Gonzalez
Senica Gonzalez

Reputation: 8182

Function call from within function, variable scope

I just want to confirm that the following will NOT work:

function f1(){
  $test = 'hello';
  f2();
}

function f2(){
  global $test;
  echo $test;
}

f1(); //expected result 'hello'

http://php.net/manual/en/language.variables.scope.php

Is there no way to just "flow" up the scope chain like you can do in Javascript? From the manual, it seems that my option for this is global or nothing at all.

I just wanted to know if that was correct.

Upvotes: 0

Views: 1090

Answers (3)

Marc B
Marc B

Reputation: 360572

The global directive makes a local function part of the top-level global scope. It won't iterate back up the function call stack to find a variable of that name, it just hops right back up to the absolute top level, so if you'd done:

$test = ''; // this is the $test that `global` would latch on to
function f1() { ... }
function f2() { ... }

Basically, consider global to be the equivalent of:

$test =& $GLOBALS['test']; // make local $test a reference to the top-level $test var 

Upvotes: 0

Toto
Toto

Reputation: 91373

Add global $test; in f1

function f1(){
    global $test;
    $test = 'hello';
    f2();
}

Upvotes: 0

Matthieu Napoli
Matthieu Napoli

Reputation: 49533

It won't work.

You can pass the variable as a parameter though :

function f1(){
  $test = 'hello';
  f2($test);
}

function f2($string){
  echo $string;
}
f1(); //expected result 'hello'

Upvotes: 4

Related Questions