给PHP包含()’d文件父变量范围
发布时间:2020-12-13 13:20:57 所属栏目:PHP教程 来源:网络整理
导读:无论如何,在父作用域中使用的包含文件是否被调用?以下示例已简化,但执行相同的工作. 本质上,函数将包含一个文件,但是希望包含文件的范围是调用包含它的函数的范围. main.php: ?php if(!function_exists('myPlugin')) { function myPlugin($file) { if(file
无论如何,在父作用域中使用的包含文件是否被调用?以下示例已简化,但执行相同的工作.
本质上,函数将包含一个文件,但是希望包含文件的范围是调用包含它的函数的范围. main.php: <?php if(!function_exists('myPlugin')) { function myPlugin($file) { if(file_exists($file) { require $file; return true; } return false; } } $myVar = 'something bar foo'; $success = myPlugin('included.php'); if($success) { echo $myResult; } included.php: <?php $myResult = strlen($myVar); 提前致谢, 编辑:解决方案 好吧,有点,谢谢Chacha102的贡献. main.php <?php class front_controller extends controller { public function index_page() { $myVar = 'hello!'; // This is the bit that makes it work. // I know,wrapping it in an extract() is ugly,// and the amount of parameters that you can't change... extract(load_file('included.php',get_defined_vars(),$this)); var_dump($myResult); } public function get_something() { return 'foo bar'; } } function load_file($_file,$vars = array(),&$c = null) { if(!file_exists($_file)) { return false; } if(is_array($vars)) { unset($vars['c'],$vars['_file']); extract($vars); } require $_file; return get_defined_vars(); } included.php: <?php $myResult = array( $myVar,$c->get_something() ); 如果要引用方法,则必须公开,但结果如预期: array(2) { [0]=> string(6) "hello!" [1]=> string(7) "foo bar" } 现在,这没有任何实际用途,我想知道如何做到的唯一原因是因为我很固执.这个想法进入了我的脑海,不会让它打败我:D <咆哮> 再次感谢Chacha102 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |