PHP:“全球”包括 [英] PHP: "Global" Include
问题描述
当前情况:
- 我的MVC框架的当前版本使用类作为控制器。
- 我的旧 MVC框架中有一些复古模块,它使用简单的扁平包含作为控制器。
- I have the current version of my MVC Framework which uses classes as controllers.
- I have some "vintage" modules from my old MVC Framework which uses simple, flat includes as controllers.
大部分简化意味着:
新版本:
<?PHP
class blaController extends baseController {
private $intVar;
function dosomethingFunction() {
$this->intVar = 123;
$this->view('myView');
}
}
?>
旧版本:
<?PHP
$globalVar = 123;
// view "controllername" is automatically shown
?>
我现在正在尝试编写一个包装器,以便能够在我的新MVC中使用旧的控制器无需重写所有内容。为此,我有一个包装器控制器:
I'm now trying to write a wrapper to be able to use my old controllers in my new MVC without having to rewrite everything. To do so, I have a "wrapper" controller:
class wrapController extends baseController {
function dosomethingFunction() {
require 'old_dosomething.function.php';
$this->view('old_dosomething_view');
}
}
(再次:这非常简单 - 非常简单 - 只是为了得到这个想法。不是实际的代码。)
(Once again: This is VERY, VERY simplified - just to get the idea over. Not actual code.)
这种方法的问题是,以前的全局变量$ globalVar现在只存在于方法dosomethingFunction中并且无法通过视图访问。
The problem with that approach is, that the previously global variable $globalVar now only exists inside of the method "dosomethingFunction" and cannot be accessed by the view.
如果我可以强制要求表现为在全局范围内以便$ globalVar将会出现这种情况再次在全球范围内可用。
This wouldn't be the case if I could force the require to behave as "in global scope" so that $globalVar would once again be available in global scope.
所以:有没有办法实现 require_global 或类似的东西?
So: Is there some way to achieve "require_global" or something similar?
(我的问题的一个解决方案是修改我的旧控制器,以一堆全局命令开始,但我更喜欢一个我不需要改变的解决方案大部分旧代码。)
(One solution for my problem would be to modify my old controllers to start with a bunch of "global" commands, but I'd prefer a solution where I don't have to change so much of that old code.)
(注意:请不要告诉我GLOBALS是坏的。它完全忽略了这个问题的重点。接受它是保持一些旧的要求代码在更新,更清洁的环境中工作。)
(Note: Please don't tell me that GLOBALS are bad. It totally misses the point of this question. Just accept that it is a requirement to keep some old code working in a newer, cleaner environment.)
推荐答案
您可以将dosomethingFunction()中定义的局部变量添加到全局范围:
You can add local variables defined within dosomethingFunction() to global scope:
class wrapController extends baseController {
function dosomethingFunction() {
require 'old_dosomething.function.php';
//begin added code
$vararr = get_defined_vars();
foreach($vararr as $varName => $varValue)
$GLOBALS[$varName] = $varValue;
//end added code
$this->view('old_dosomething_view');
}
}
注意,为了使其按预期工作,你应该在使用函数中的任何其他东西之前调用require。 get_defined_vars()只返回当前作用域中的变量,因此不需要array_diff hacks。
Note, that for this to work as expected, you should call require before using any other thing in the function. get_defined_vars() returns only variables from the current scope, so no array_diff hacks are needed.
这篇关于PHP:“全球”包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!