note 98835 deleted from function.include by peehaa
| From: | peehaa@php.net | Date: | Fri, 09 Dec 2016 22:53:09 +0000 |
| Subject: | note 98835 deleted from function.include by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208396@lists.php.net to get a copy of this message | ||
Note Submitter: emanueledelgrande ad email dot it
----
About the problem to include a script in the global scope, after many tests with different
solutions, I reached my point. I post it in the hope it may be useful.
At first I built my "globalScopeSimulator" class, but an include called inside a class is
not the best solution: if it contains some user code, the user will access to the $this reserved
variable and even to all the private members... Critical issue!
That's why I turned back into a function solution.
Another advantage is that I didn't have to make use of the deprecable "global"
keyword, since I *imported* the global scope inside the function, with the extract() function.
Using the EXTR_REFS flag this trick does not waste memory, since the extracted variables are not a
copy, but a reference to the global ones.
<?php
function global_include($script_path) {
// check if the file to include exists:
if (isset($script_path) && is_file($script_path)) {
// extract variables from the global scope:
extract($GLOBALS, EXTR_REFS);
ob_start();
include($script_path);
return ob_get_clean();
} else {
ob_clean();
trigger_error('The script to parse in the global scope was not found');
}
}
?>
Hope it helps... :)
Cheers and happy coding!