I’m 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, and 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:
<?php
function latestProducts($amount = 6){
}
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 couldn't 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 I got the same result.)
What is my mistake? I know it’s simple; I just can’t see clearly right now.
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:
global $xml;at the start of the function$GLOBALS['xml']Note that when using a good OOP-style architecture these kind of problems can often be avoided, e.g.
$xmlwould be a property of class instances that need direct access to the DOM object.