Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使我的函数集变量在当前范围内_Php_Variables - Fatal编程技术网

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_数组)