An extension of what Quano offers:
Take it one step further and include the variables in the global execution area (which otherwise would have to be called with global internal include elements). The idea is that you want the inclusion function to work as if it were included in your main application area or your definition area.
Consider this class:
class PHPInclude { private static $globalsList = array( 'GLOBALS','_SERVER','_GET','_POST','_FILES', '_REQUEST','_SESSION','_ENV','_COOKIE' ); public static function phpInclude($file,$variables=array()) { if ( file_exists($file) ) { $globs = array(); foreach ( $GLOBALS as $key => $value ) { if ( !in_array($key,sefl::$globalsList) ) { array_push($globs,$key); } } foreach ( $globs as $key ) { global $$key; } foreach ( $variables as $variable ) { global $$variable; } unset($globs,$key,$value); ob_start(); include $file; return ob_get_clean(); } return ''; } }
Use it as follows:
$foo = 'bar'; function testScope() { $woo = 'sah'; PHPInclude::phpInclude('file.phtml',array($woo)); }
In the example, $foo will be automatically turned on because it is in the global scope, and $woo added because it is in the local scope.
I have not tested $this as an arbitrary variable, but my spider feelings tell me it will not work (warning) .
source share