2

I declared a new variable $var at the top of my document. Afterwards, I called a function which should output this variable.
Unfortunately, I get the following message:

Notice: Undefined variable: var

This is my code:

$var = "abc";

func ();
function func() {
    echo $var;
}
Clay
  • 4,700
  • 3
  • 33
  • 49
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • you should pass the $var variable to the function, for example func($var) – Webster Jan 10 '16 at 14:11
  • 1
    Review [PHP's documentation on variable scope](http://php.net/manual/en/language.variables.scope.php). It is different from other languages (like JavaScript for example). – Michael Berkowski Jan 10 '16 at 14:14

3 Answers3

2

In PHP, functions cannot access variables that are within the global scope unless the keyword global is used to 'import' the variable into the function's scope.

You would fix it by doing this:

function func() {
    global $var;
    echo $var;
}

Read more about scoping here: http://php.net/manual/en/language.variables.scope.php

Any variable used inside a function is by default limited to the local function scope.

In PHP global variables must be declared global inside a function if they are going to be used in that function.

Global variables can also be accessed using $GLOBALS although I would avoid using that unless absolutely necessary.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.

Worth mentioning:

It's worth linking to this discussion on globals and why you may not want to use them: Globals are evil . I'd say there is a preference to use classes instead, or simply pass in the variable as an argument to the function. I won't say not to use globals but at the very least be mindful of its use.

Community
  • 1
  • 1
Clay
  • 4,700
  • 3
  • 33
  • 49
0

This is because the scope of the variable, either you define it as global, or you pass it as a parameter.

Check the comments under this post: Variables Scope

Community
  • 1
  • 1
Yazid Erman
  • 1,166
  • 1
  • 13
  • 24
0

The scoping of your variable is wrong. You will need to either pass it as a function parameter or declare it as Global in the function. Please review function scoping.

You could do something like this:

$var = "abc";

func ();
function func() {
    global var;
    echo $var;
}
Jonathan Musso
  • 1,374
  • 3
  • 21
  • 45