Jump to content

acessing outher function variable from variable function


Goat

Recommended Posts

It is a bit hard to explain so I'll just show an example:


function foo()
{
   $a = "changed by variable function";
}

function bar($var_function)
{
   $a = "original value";
   $var_function();
   echo($a); 
}

bar(foo); // outputs "original value", not "changed by variable function"

 

I can access global scope using global keyword, but there does not seem to be a way to access local function variables. Any ideas?

 

regards,

 

Goat

 

You would need to pass a reference of $a. This way instead of actually passing the value of $a you're passing the location in memory of $a.

 

function foo(&$a)
{
   $a = "changed by variable function";
}

function bar($var_function)
{
   $a = "original value";
   $var_function($a);
   echo($a); 
}

echo bar('foo');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.