看来您的框架过于依赖非 OOP 的内部结构。这不是一种更可取的构建方式,但您可以通过循环浏览变量列表并使它们成为您的类/实例范围的一部分来做您想做的事情。这里一个相当有用的函数是get_defined_vars();
假设您有文件 a.php、b.php 和 c.php。每个看起来像这样:
一个.php:<?php $a = "AAAAAA";
b.php:<?php $b = "BBBBBBBBBB";
c.php:<?php $c = "CCCCCCCCCCCCCCCCCCCCCCCCCCC";
class mystuff {
function include_with_vars( $____file ) {
// grab snapshot of variables, exclude knowns
$____before = get_defined_vars();
unset( $____before['____file'] );
// include file which presumably will add vars
include( $____file );
// grab snapshot of variables, exclude knowns again
$____after = get_defined_vars();
unset( $____after['____file'] );
unset( $____after['____before'] );
// generate a list of variables that appear to be new
$____diff = array_diff( $____after, $____before );
// put all local vars in instance scope
foreach( $____diff as $variable_name => $variable_value ) {
$this->$variable_name = $variable_value;
}
}
function __construct($file = NULL){
$this->include_with_vars( "a.php" );
$this->include_with_vars( "b.php" );
$this->include_with_vars( "c.php" );
}
}
$t = new mystuff();
echo "<PRE>";
print_r( $t );
该程序现在将从您的 include() 指令中获取局部变量并将它们放在类范围内:
mystuff Object
(
[a] => AAAAAA
[b] => BBBBBBBBBB
[c] => CCCCCCCCCCCCCCCCCCCCCCCCCCC
)
换句话说,文件 a.php( $a
) 中的局部变量现在是$t->a
.