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.
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 couldextract()that in your function: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.