如何在包含页面(而不是包含页面)上声明变量?

时间:2013-08-28 17:16:38

标签: php php-5.3 php-include

我知道我可以使用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数组将继续增长)。还有更好的方法吗?

注意:页面是从属性文件中的列表动态包含的,因此代码将不会提前知道要包含哪些

1 个答案:

答案 0 :(得分:1)

假设文件中没有名为$_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';