Getting names of variables passed to functions...

Getting names of variables passed to functions...

am 10.10.2007 13:11:17 von BoneIdol

Anyway to do it? I know you can use a variable's contents as a
variable name with $$name, but I'd like to do it the other way around.

function foo($bar)
{
return $bar;
}

$name = foo($variable_name);
?>

I'd like the function foo to return a string of the variable name
passed to it, in this case 'variable_name'. A friend of mine who does C
++ programming says that pointers are the way to go here, but as far
as I know PHP doesn't support them.

Re: Getting names of variables passed to functions...

am 12.10.2007 23:31:02 von Janwillem Borleffs

BoneIdol wrote:
> I'd like the function foo to return a string of the variable name
> passed to it, in this case 'variable_name'. A friend of mine who does
> C ++ programming says that pointers are the way to go here, but as far
> as I know PHP doesn't support them.
>

A (not fullproof) way is the following:

function foo($bar) {
$keys = array_keys($GLOBALS);
$values = array_values($GLOBALS);
$index = array_search($bar, $values, true);
if ($index !== false) {
return $keys[$index];
}
}

$variable_name = 'foo';
$name = foo($variable_name);
print $name;

Of course, this only works when each variable has a unique value...


JW

Re: Getting names of variables passed to functions...

am 13.10.2007 14:15:34 von Thomas Mlynarczyk

Also sprach BoneIdol:

> Anyway to do it?

No. You could try this (not tested, though):

$foo = 'bar';
doSomething( compact( 'foo' ) );

function doSomething( $aVar )
{
list( $sVarName, $xVarValue ) = each( $aVar );
echo "The variable is called $sVarName and has the value $xVarValue.\n";
}

With objects in PHP5 you can use the __set()/__get()/__call() magic
functions (not tested either):

class Foo
{
private $_aVars = array();

public function __set( $sName, $xValue )
{
echo "Setting $sName to value $xValue.\n";
$this->_aVars[$sName] = $xValue;
}

public function __get( $sName )
{
echo "Getting $sName.\n";
return $this->_aVars[$sName];
}
}

$oFoo = new Foo;
$oFoo->bar = 'baz';
echo $oFoo->bar;

But why do you need such a functionality? Maybe there is a solution to your
problem (whatever it is) which does not require it?

Greetings,
Thomas