How to force forced execution of a PHP file in a global scope?

I have a php file, say include.php, which has the following contents:

<?php $myVar = "foo"; ?> 

Now I want to create a class called GlobalInclude that can include a file in the global scope:

 class GlobalInclude { public function include( $file="include.php" ) { #do something smart include $file #do something smart } } 

In the current form, the variable $ myVar will be available only inside the scope of the include function. I want to do something like:

 GlobalInclude::include( "include.php" ); echo $myVar; 

Exit foo

Any ideas on how I can do this?

+4
source share
4 answers

I think I would update the answer here. I wrapped the application entry in a try catch and threw a IncludeInGlobalException with the file name as the message. Then in the catch block I included the file.

0
source
+2
source

Awfully ugly hack:

 $GLOBALS[$myVar] = $myValue; 

in include.php (or any other file that you use).

0
source

EDIT: Sorry, I read your original post incorrectly. You can do this using get_defined_vars to capture all the variables in the current scope and return them:

 public function includeAndGetVars($file) { include $file; return get_defined_vars(); } 

Then, after calling your function, use extract to display the results in the current area:

 extract(includeAndGetVars("include.php")); echo $myVar; 
0
source

All Articles