March 4, 2012

PHP cant use variable defined outside functions

Question by Adonis K.

Im working on a project (simple xml CMS) just to learn some basic PHP.

first i include a config.php file which contains information about the CMS, then i include a route.php for the url routing and after that i include a functions.php file which is pretty similar to the wordpress’ one (contains all the functions to for example load posts, tags, categories etc).

The structure looks like this:

    function products($search = FALSE, $query= '', $page = 1, $results = 5){
    }

    function getProductById($id){
    }

    function getProductTitleById($id){
    }

    function getProductByExcerpt($excerpt){
    }

    function getProductTitleByExcerpt($excerpt){
    }

    function getPost($id, $title, $description, $category, $excerpt = FALSE){
    }

    function getTitle(){
    }

    function breadcrumb($params, $first){
    }

    function pagination($page, $pages){
    }
?>

In config.php file i also use this code:

$xml = simplexml_load_file('products.xml') or die('The Product xml file couldnt be loaded.');

But when i try to access $xml from within the functions i prepared in functions.php, i get a undefined variable notice. (i also tried placing the $xml variable inside the functions.php before the definition of the functions but got the same result).

Can someone please tell me my mistake? I know its simple, i just cant see clearly right now.

Thanks in advance.

Answer by Another Code

You have a scoping issue. The variables declared in the global scope aren’t visible inside your functions. The manual explains what you can do about it. An overview:

  • Import the variable from the global scope into the local scope of your function with global $xml; at the start of the function
  • Store the variable as a key of the global variables superglobal, i.e. $GLOBALS['xml']
  • Make the variable a static member of a class or create a singleton construction
  • Pass the variable as an argument to every function that needs it

Note that when using a good OOP-style architecture these kind of problems can often be avoided, e.g. $xml would be a property of class instances that need direct access to the DOM object.

Answer by Starx

Functions or methods do not have scopes outside them. In order to use a variable declared outside. Using global keyword, to tell the server to use the variable defined in higher scope.

$varname = "value";
function yourfunctionname() {
    //In order to use the variable declare you want to use the globally declared 
    global $varname;
    //now $varname will have "value` as its value

   //continue with your logic
}
...

Please fill the form - I will response as fast as I can!