I know that I can use get_defined_vars()
to get the variables declared on a page, but I only want the variables declared on the include page.
I know I can do this:
//Get variables of containing page only
$mainPage = get_defined_vars();
//Include new page
include "somepage.php";
//Get variables combined for include and my page
$sothPages = get_defined_vars();
//Find out keys included page
$includeKeys = array_diff_key( $bothPages, $mainPage );
//Now loop through and use only those keys
....
But that seems a little messy and slow (especially if I include multiple pages and have to redo this for each one - the $mainPage
array will keep growing). Is there a better way?
NOTE: The pages are included dynamically from a list in a properties file, so the code won't know ahead of time which to include
Assuming you don't have a variable named $_filename
in the file:
function getVarsFromPHPFile($_filename) {
include $_filename;
unset($_filename);
return get_defined_vars();
}
$includeKeys = getVarsFromPHPFile('somepage.php');
This should work provided that you aren't declaring the variables as global
.
Of course, if you change somepage.php
to return an array (as in return array(...);
), you could just do $includeKeys = include 'somepage.php';
instead.