Getting names of variables passed to functions...

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.

<?php
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.
BoneIdol [ Mi, 10 Oktober 2007 13:11 ] [ ID #1841346 ]

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

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
Janwillem Borleffs [ Fr, 12 Oktober 2007 23:31 ] [ ID #1843497 ]

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

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
Thomas Mlynarczyk [ Sa, 13 Oktober 2007 14:15 ] [ ID #1844117 ]
PHP » alt.php » Getting names of variables passed to functions...

Vorheriges Thema: Day Five of the Hatter House Hunt
Nächstes Thema: Ahhh, Inspiration!