How do I fix Undefined variable error in PHP

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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 follow.

<?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 following error when I have run this file in 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

Can anybody help me to fix issue regarding it?

Answers

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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/20391807/how-do-i-fix-undefined-variable-error-in-php

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils