这是一个干净的编码问题。
在父文档中声明了一些变量后,以及require
语句之后:
$My_Variable = 'Something here';
$My_Variable_2 = 'Something else here';
require __DIR__.'/test2.php'; // More stuff will happen to $My_Variable and $My_Variable_2 here...
代替原始的require语句,我想调用执行require
语句的clean语法函数:
Require_Script($Arguments);
Require_Script()
函数看起来像这样:
function Require_Script($Arguments) {
// Some other code here;
require __DIR__.'/test2.php';
}
我注意到,除非我小心点,父文档中声明的变量(在不同上下文中可能是不同的变量)将在test2.php
中进行操作(以及were当我使用原始的include
语句时对该require
可用)在test2.php
中不再可用-大概是因为require
语句现在处于不同的范围内。
这里是实际情况。这里有几个包括:
test2.php:
$My_Variable .= ' which has been upgraded';
$My_Variable_2 .= ' which has also been upgraded';
test3.php:
$My_Variable .= ' not once but twice.';
$My_Variable_2 .= ' also not just once but twice.';
这是父母文件:
$My_Variable = 'This is my variable';
$My_Variable_2 = 'This is my other variable';
echo '<p>'.$My_Variable.'</p>'; // This is my variable
echo '<p>'.$My_Variable_2.'</p>'; // This is my other variable
***********
***********
require __DIR__.'/test2.php';
echo '<p>'.$My_Variable.'</p>'; // This is my variable which has been upgraded
echo '<p>'.$My_Variable_2.'</p>'; // This is my other variable which has also been upgraded
***********
***********
function My_Require_Function($logicVariables) {
foreach ($logicVariables as $key => $value) {
${$key} = $value;
global ${$key};
}
require __DIR__.'/test3.php';
}
My_Require_Function(['My_Variable' => $My_Variable, 'My_Variable_2' => $My_Variable_2]);
echo '<p>'.$My_Variable.'</p>'; // This is my variable which has been upgraded not once but twice.
echo '<p>'.$My_Variable_2.'</p>'; // This is my other variable which has also been upgraded also not just once but twice.
所以,它有效。但是肯定有更好的方法吗?
此方法使用:
extract()
我的问题是:
[有哪些(更好)更好的替代方法可以使我在语法上替代
global
带有一个合并了require语句的函数,看起来像:
require __DIR__.'/test2.php'
我真的很喜欢@Barmar在上面的评论中的观察:
包含文件应定义函数,您可以在父函数中调用这些函数脚本,然后将变量作为参数传递。
因此,我开始考虑一种方法,而不是简单地Require_Script($Arguments)
几行代码来修改父文档中的变量,而是including
然后运行include
。
这将需要4个步骤:
父文档中的一个函数,它接受要包含的两个函数的名称作为参数和包含将被馈送到该远程函数的参数值的关联数组
远程功能(在function
文件中)到included
来自提交的关联数组的所有变量
远程函数(在extract()
文件中)以处理所有这些变量,然后重新构建其自己的关联数组并返回
父文档included
返回的关联数组中的所有变量
最终看起来像这样:
test4.php
extract()
父文档:
function test4($logicVariables) {
extract($logicVariables);
$My_Variable .= ' not once but twice.';
$My_Variable_2 .= ' also not just once but twice.';
return ['My_Variable' => $My_Variable, 'My_Variable_2' => $My_Variable_2];
}
真正的好消息是此方法有效,并且它[[不需要需要自定义的function My_New_Require_Function($Include_Name, $logicVariables) {
require __DIR__.'/'.$Include_Name.'.php';
return $Include_Name($logicVariables);
}
$My_Variables = ['My_Variable' => $My_Variable, 'My_Variable_2' => $My_Variable_2];
$My_Variables = My_New_Require_Function('test4', $My_Variables);
extract($My_Variables);
或变量变量或extract()
。 (尽管它仍然需要将关联数组提交给该函数。)
global