Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file includes inside function, need to retain global variables. (Trying to wrap HTML comments)

Tags:

php

In an attempt to speed up my workflow and help the back end guys with integration (I'm a front end dev) I'm attempting to extend the file includes function by wrapping comments around each file include to output it's filename:

function include_module($path) {
    echo "\n\n<!-- MODULE: ".basename($path, '.php')." -->\n";
    include($path);
    echo "\n<!-- /MODULE: ".basename($path, '.php')." -->\n\n";
}   
include_module('form-controls.php');

However this results in the loss of access to any variables set outside the function. I know I can do:

global $var

But that will only give me access to $var (I'm aware I could do $var['var1'], etc), is there any way to do 'global all' or can anyone think of a different approach to wrap the comments?

Cheers :)

like image 969
4lun Avatar asked May 16 '12 13:05

4lun


2 Answers

Try this:

function include_module($path) {
    foreach($GLOBALS as $name => $value) global $$name;
    echo "\n\n<!-- MODULE: ".basename($path, '.php')." -->\n";
    include($path);
    echo "\n<!-- /MODULE: ".basename($path, '.php')." -->\n\n";
}   
include_module('form-controls.php');
like image 122
JoolzCheat Avatar answered Oct 03 '22 11:10

JoolzCheat


You can use the following to access the globals.

extract($GLOBALS, EXTR_REFS); 
like image 21
Christian Huber Avatar answered Oct 03 '22 11:10

Christian Huber