views:

37

answers:

1

Hello, i've been thinking if something like this is possible.

// this creates a variable $test in the scope it was called from
function create_var() {}

class A {
  function test()
  {
    create_var();
    // now we have a local to var() method variable $test
    echo $test;
  }
}

So, the question is, can a function create_var() create a variable outside of its scope, but not in a global scope? Example would be the extract() function - it takes an array and creates variables in the scope it was called from.

+3  A: 

Nope, this is not possible. It's possible only to access the global scope from within a function.

You could make create_var() return an associative array. You could extract() that in your function:

function create_var() 
 { return array("var1" => "value1", "var2" => "value2"); }

class A {
function test()
{
    extract(create_var());
    // now we have a local to var() method variable $test
    echo $test;
}
}

Something a bit closer to what you want to do is possible in PHP 5.3 using the new closures feature. That requires declaring the variables beforehand, though, so it doesn't really apply. The same goes for passing variable references to create_var(): create_var(&$variable1, &$variable2, &$variable3....)

A word of warning: I can think of no situation where any of this would be the best coding practice. Be careful when using extract() because of the indiscriminate importing of variables that it performs. It is mostly better to work without it.

Pekka
Thanks, i guess i knew all that, i was just secretly hoping it was possible. Well, i wouldn't use it with extract, i basically needed a function to extract some of the parameters, comming from POST or GET or whatever. And since i only want to allow extract() to play with some specific variables in these arrays, the easiest solution is like you provided. But still, would be nice if i could just do something like: extractvars('field1,field2,field3'), because things like that simply look more clean to me than a bunch of array stuff ;]
Marius