Reputation: 1744
My project uses a template system to put the pages together and there are many variables involved. Usually the template is loaded directly from an index file and not from within a function.
However, at the moment I'm simply making this function to display an error page:
function show_error($error){
global $root;
global $template;
$content=$root."/includes/pages/error_page.html.php";
include $root . $template;
exit();
}
However, since the template uses many variables outside the scope of this function, it just comes up with lots of variable not found errors.
Is there a way of simply making all global variables available inside of a function? I'd rather not individually declare all possible variables inside as it would be quite tedious and because I am often adding more variables in the template.
Upvotes: 0
Views: 105
Reputation: 1787
You can use extract()
to import all globals into function scope
$foo = 'bar'; // global scope
function test(){
extract($GLOBALS, EXTR_OVERWRITE, 'g'); // import with prefix to avoid mess
echo $g_foo; // outputs: bar
}
Read more: http://php.net/manual/ru/function.extract.php
Upvotes: 1
Reputation: 4334
If $content and $root are in global context, you can access them inside the function by adding this to the function before you use them:
global $content, $root;
Upvotes: 0