On Tue, August 15, 2006 1:19 pm, Chris W. Parker wrote:
> After some "intense" searching of Google I found one example at
> http://us2.php.net/language.variables on how to get the name of a
> variable. But it looks pretty expensive.
>
> <?php
>   function vname(&$var, $scope=false, $prefix='unique',
> $suffix='value')
>   {
>    if($scope) $vals = $scope;
>    else      $vals = $GLOBALS;
>    $old = $var;
>    $var = $new = $prefix.rand().$suffix;
>    $vname = FALSE;
>    foreach($vals as $key => $val) {
>      if($val === $new) $vname = $key;
>    }
>    $var = $old;
>    return $vname;
>   }
> ?>
>
> Anyone aware of a simple language construct(?) that can do this? I'm
> on
> PHP 4.3.9.

There is no function that can do this, because any given variable may
have several different "names" based on the current scope.

$foo = 5;
function bar ($x) { return baz ($x); }
function baz ($z) {
  echo "What's your name?<br />Who's your daddy?<br />\n";
  echo vname($z);
}
$foobar = $foo;
bar($foobar);

Do you expect 'x' or 'foo' or 'foobar' as the output of your vname()
function?

I don't even know what you're going to get from reading that hack
above, much less what to expect.

You can come at this "backwards" by passing in the NAME of a variable,
and using variable variables within the function to get the value.

But 99.9% of the time one does that, one should have been using an
array in the first place, and not variable variables.

If you want to associate a name with a value throughout your program,
you should DEFINITELY be using some kind of structure designed for
that.

Associative arrays work very well for this.

Objects with properties also work.

If the names are not predictable, the array solution is probably best,
as there is movement in the PHP Internals list that may (or may not)
make it impossible to dynamically add a property to an object.  I've
lost track of where that thread ended, so apologies if this is a
non-issue.

The array is probably the more correct construct for un-predictable
names, unless there are pre-existing instances that are immutably and
inherently already bound to the name/value you wish to store.

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to