我知道我可以使用get_defined_vars()
来获取在页面上声明的变量,但我只希望在include页面上声明变量。
我知道我能做到:
//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
....
但这似乎有点混乱和缓慢(尤其是如果我包含多个页面,并且必须为每个页面重做这一操作——$mainPage
数组将不断增长)。有更好的方法吗?
注意:页面是从属性文件的列表中动态包含的,因此代码不会提前知道要包含哪个页面
假设文件中没有名为$_filename
的变量:
function getVarsFromPHPFile($_filename) {
include $_filename;
unset($_filename);
return get_defined_vars();
}
$includeKeys = getVarsFromPHPFile('somepage.php');
如果您没有将变量声明为global
,这应该会起作用。
当然,如果您更改somepage.php
以返回一个数组(如return array(...);
),您可以改为使用$includeKeys = include 'somepage.php';
。