1

Been struggling to make some simple code work, but face a problem with the global/local reach of one variable.

Here is the code I try to get to work. This code is contained in a PHP file called by an AJAX GET procedure from Javascript. None of the GET variables appears in the below chunks of code.

$location = "./Treewindow/tree_structure.xml";

function openXML($url) {
if (file_exists($url)) {
    $xml = simplexml_load_file($url);
    } 
else {
    echo("Failed to open XML at ".$url);
    exit;
    }
}

function cubicleAvailableSpace() { 
    openXML($location);
}

When I call the last function:

cubicleAvailableSpace();

I get:

Failed to open XML at 

Why is the variable $location not recognized in the function cubicleAvailableSpace()?! I thought it would be considered as "visible" from all functions within this PHP code...

Now, I am sure this is easy, but I tried the whole afternoon to make this work... Looked all around the place, but could not find any reply which helped me (though there are many such cases in this website) Of course, when I replace the variable by its actual value ("./Treewindow/tree_structure.xml"), everything works: the XML file is at the right place :-)

Can you help me find what's wrong and make this $location variable visible in both functions ?

Thanks

Fabien
  • 11
  • 3
  • 1
    You'd have to declare it as `global $location;` inside your function if you wanted it imported into the scope of that function. – nickb Jul 31 '13 at 18:54
  • I would take an OO approach to this situation. Like here http://stackoverflow.com/questions/2483675/in-php-how-to-call-a-variable-inside-one-function-that-was-defined-previously – Kevin Lynch Jul 31 '13 at 18:58

1 Answers1

3

try this

function cubicleAvailableSpace() { 
  global $location;
  openXML($location);
}

you declared the variable outside the function so it is not readable inside.

ROMMEL
  • 524
  • 2
  • 10
  • Thanks for the ideas, but somehow the global $location does not work as planned. In fact, I just found out that I can pass the $location variable as a parameter to the cubicleAvailableSpace($location). Solves my problem. – Fabien Jul 31 '13 at 21:39