0

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.

2
  • your template should not be accessing variables outside of its scope Commented May 16, 2017 at 12:38
  • 1
    you might benefit from learning how to actually do some basic templating in PHP: chadminick.com/articles/simple-php-template-engine.html Commented May 16, 2017 at 12:50

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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; 

2 Comments

Sorry I have edited my question, that is already included. It's the many other variables that the template uses which is causing the issue as I would have to declare them all.
If you are using tons and tons of global variables, you should use $GLOBALS.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.