0

I want to declare a global variable using PHP and be used inside functions.

I have tried:

$var = "something";
function foo()
{
    echo $var;
}

yet I receive an error stating that the $var is undefined.

How can I solve this?

Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
sikas
  • 5,435
  • 28
  • 75
  • 120
  • The recommended approach would generally be "don't do that", e.g. http://stackoverflow.com/questions/484635/are-global-variables-bad – El Yobo Nov 28 '10 at 06:05

2 Answers2

7
$var = "something";
function foo()
{
    global $var;
    echo $var;
}

use the term "global" when you need to use variables that were declared outside your function scope.

misterjinx
  • 2,606
  • 3
  • 27
  • 29
5

PHP variables have function scope. I.e., variables inside a function can't be accessed from outside it and global variables can't (by default) be accessed from inside functions. While using the global keyword inside functions to im-/export variables is a solution, you should not do it. Functions should be self-contained; if you need a value inside a function, pass it as a parameter, if the function needs to modify global values, return them from the function.

Example:

function foo($arg)
{
    echo $arg;
}
$var = "something";
foo($var);

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

Gordon
  • 312,688
  • 75
  • 539
  • 559
deceze
  • 510,633
  • 85
  • 743
  • 889
  • @Gordon +1 for additions. But, of course, in the end `global` has won yet again. *sigh* – deceze Nov 27 '10 at 13:18
  • 1
    @Gordon I think you scared him off with "Dependency Injection", he wanted a little finger and you threw the whole arm at him. ;o) – deceze Nov 27 '10 at 13:29