-5

Why is an empty line printed instead of 5?

function test()
{   
 echo "$a <br/>";   
}

$a = 5;
test();
user1007632
  • 167
  • 2
  • 2
  • 8

2 Answers2

6

Functions in PHP do not inherit global scope or parent scope (unless using an anonymous function with use()).

You can use the global keyword to access them.

function test()
{
 global $a;   
 echo "$a <br/>";   
}

CodePad.


Jared Farish also points out the use of the global associative array $GLOBALS which holds all global variables and which, like any super global such as $_POST, $_GET, etc, is in scope everywhere.

function test()
{   
 echo "$GLOBALS[a] <br/>";   
}

$a = 5;
test();

CodePad.


You could use an anonymous function...

$a = 5;

$test = function() use ($a) {
    echo $a;
};

$test();

CodePad.


As a footnote, try not to rely on global variables. They can be a sign of poor program design if you overly rely on them.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    I know, I know, but OP: *Please refrain from unnecessary `global` variables*. – Jared Farrish Oct 30 '11 at 23:28
  • Also, `$GLOBALS['a'] = 5;` could be used with `global $a;`. Though I will admit I haven't mastered the difference. – Jared Farrish Oct 30 '11 at 23:29
  • @JaredFarrish: Oh yeah, though I've never used `$GLOBALS`. Made an edit :) – alex Oct 30 '11 at 23:30
  • IMHO, even using 'use()' will not give you access to global scope you can only access the value of variables _at the time they are passed_, unless passed by reference. –  Oct 30 '11 at 23:35
  • @JaredFarrish I sacrificed the love of '$GLOBALS' for beauty of stable code. –  Oct 31 '11 at 03:37
2

you forgot to use the global

function test()
{   
  global $a;
  echo "$a <br/>";   
}

$a = 5;
test();
samura
  • 4,375
  • 1
  • 19
  • 26