0

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.

4
  • I know I can just pass $test into the f2. This is just for curiosity more than anything. Commented May 4, 2011 at 16:03
  • Ok, I just added the code because I wasn't sure, and that's better if anybody else has the same question and see this page. Commented May 4, 2011 at 16:05
  • Try it... That should tell you really quick (much quicker than asking the question here) Commented May 4, 2011 at 16:37
  • @ircmaxell Thanks. Obviously, it would be pointless for me to write an example code without having some knowledge of what it does or doesn't do. The question was more the point or, "is there way to do it" without going into the global scope. Commented May 4, 2011 at 16:56

3 Answers 3

4

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I just made a comment since I figured everyone would say that ;) Thanks for confirming.
0

Add global $test; in f1

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

Comments

0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.