Php 使我的函数集变量在当前范围内
能做到吗Php 使我的函数集变量在当前范围内,php,variables,Php,Variables,能做到吗 function my_function(&$array){ // processing $array here extract($array); // create variables but not here } function B(){ $some_array = array('var1' => 23423, 'var2' => 'foo'); my_function($some_array); // here I want
function my_function(&$array){
// processing $array here
extract($array); // create variables but not here
}
function B(){
$some_array = array('var1' => 23423, 'var2' => 'foo');
my_function($some_array);
// here I want to have $var, $var2 (what extract produced in my function)
}
例如,parse_str()能够做到这一点。Edit在我的第一个答案中没有思考 答案是否定的;您可以在函数
B
中移动extract
调用,仅此而已
顺便说一句,有了你问题的更多背景知识,我可以改进我的答案:)这是可行的,但它不会提取到它被称为的上下文中,只是全局
function my_function($array){
foreach($array as $key => $value) {
global $$key;
$$key = $value;
}
}
然而,我不推荐它。将一堆东西解包到全球范围内很少是一个好主意(但并非绝对不是)
至于将调用的函数提取到作用域中,我认为这是不可能的,或者至少不值得这样做。我想如果您想创建一个单行程序,您需要返回一个值
function my_function($array){
// processing $array here
// Return the processed array
return $array;
}
function B(){
$some_array = array('var1' => 23423, 'var2' => 'foo');
// If you don't pass by reference, this works
extract(my_function($some_array));
}
PHP不允许您使用另一个函数的作用域,这是一件好事。如果您在实例化对象中,您可以使用
$this->
处理属性,但我想您已经知道了这一点。您不能将my_function()
与extract()
交换?@alex:我假设my_function
对extract
ed变量进行一些处理,我可以在my_function之后运行extract,但我想知道我是否能在自己的时间内做到这一点function@Alex:我建议在my_function
之后执行extract
,这听起来是最简单的解决方案。我想最好的方法是将list()
与extract
结合使用,或者,你知道,使用extract
,哪种方法可以做到这一点呢:-PHow about$GLOBALS[$key]=$value代码>?$GLOBALS
包含所有全局变量。做$GLOBALS['test']=12代码>表示$test
现在是12
。尽管您可能需要global$test
first.ok,那么正确的答案应该是“no”:)看来php对我们隐藏了一些东西,但这不起作用,另一个函数仍然需要global$var1,$var2
让它起作用。@Rocket“我已经有一段时间没有使用PHP了。感谢您重新教育我:)您必须使用my_函数
return$array
才能使其正常工作。在本例中,它通过引用编辑数组,因此需要执行:my_函数($some_数组);提取($some_数组)代码>