Make my function set variables in current scope

Can this be done?

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)
}

For example, parse_str () can do this.

+3
source share
3 answers

Edit I did not think in my first answer.

The answer is no; you can move the call extractinside your function Babout it.

Btw, with some additional background of your problem, I could improve my answer :)

+2
source

This works, but it is not retrieved into the context that it was calling, just global ...

function my_function($array){
  foreach($array as $key => $value) {
      global $$key;
      $$key = $value;
  }
}

CodePad .

However, I would not recommend it. It is rarely (but not exclusively never) a good idea to unpack a bunch of things into a global area.

, , , , , .

+1

I think you need to return a value if you want to do a single line.

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 does not allow you to play with the scope of another function, which is good. If you were in an object-based object, you can use $this->to work on the property, but I think you already know that.

+1
source

All Articles