How do I fix "Undefined variable" error in PHP?

compiler-errors, error-handling, php, runtime-error, syntax-error

Solution

The first error (`$x` is undefined) is because globals are not imported into functions by default (as opposed to "super globals", which are).

You need to tell your function you're referencing the global variable `$x`:

function myTest()
{
  global $x; // $x refers to the global variable

  $y=10; // local scope
  echo "<p>Test variables inside the function:<p>";
  echo "Variable x is: $x";
  echo "<br>";
  echo "Variable y is: $y";
}

Otherwise, PHP cannot tell whether you are shadowing the global variable with a local variable of the same name.

The second error (`$y` is undefined), is because local scope is just that, local. The whole point of it is that `$y` doesn't "leak" out of the function. Of course you cannot access `$y` later in your code, outside the function in which it is defined. If you could, it would be no different than a global.

Problem

Today, I have started to learn PHP. And, I have created my first PHP file to test different variables. You can see my file as follows. ``` <?php $x = 5; // Global scope function myTest() { $y = 10; // Local scope echo "<p>Test variables inside the function:<p>"; echo "Variable x is: $x"; echo "<br>"; echo "Variable y is: $y"; } myTest(); echo "<p>Test variables outside the function:<p>"; echo "Variable x is: $x"; echo "<br>"; echo "Variable y is: $y"; ?> ``` I have found the following errors when I have run this file in the browser. Notice: Undefined variable: x in /opt/lampp/htdocs/anand/php/index.php on line 19 Notice: Undefined variable: y in /opt/lampp/htdocs/anand/php/index.php on line 29 How can I fix the issue regarding it?

Original source