Reputation: 68004
Can it 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() is able to do this.
Upvotes: 3
Views: 147
Reputation: 60747
I guess you need to return a value if you want to make a one-liner.
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 doesn't allow you to play with the scope of another function, and that is a good thing. If you were in an instanciated object, you could use $this->
to work on a property, but I guess you already know this.
Upvotes: 1
Reputation: 490263
This works, but it doesn't extract into the context it was called, just the global...
function my_function($array){
foreach($array as $key => $value) {
global $$key;
$$key = $value;
}
}
However, I wouldn't recommend it. It's rarely (but not exclusively never) a good idea to unpack a bunch of stuff into the global scope.
As far as extracting into the scope the function was called, I don't think it's possible, or at least, worth doing.
Upvotes: 1
Reputation: 173572
Edit Wasn't thinking in my first answer.
The answer is no; you can move the extract
call inside your function B
, that's about it.
Btw, with some more background of your problem I could improve my answer :)
Upvotes: 2