-1

i am new in PHP and i had a question: how can i access a variable declared in a function from global scope?

function test(){
   $x = 6;
   $y = 5;
   return $x;   
}

test();
echo $GLOBALS['y'];

I want to access variable y in global. Thank you!

Tom
  • 445
  • 1
  • 4
  • 10
  • 1
    Possible duplicate of [How to declare a global variable in php?](http://stackoverflow.com/questions/13530465/how-to-declare-a-global-variable-in-php) – manniL May 22 '16 at 09:28

1 Answers1

3

Either use $GLOBALS['y'] in the function (it's super-global, so it's available anywhere) or define global $y; in the beginning of the function.

Note: using such global variables is a bad style, better return the value (or modify it by passing it as a by-reference parameter to the function)

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89