note 49997 deleted from language.variables by googleguy
| From: | googleguy@php.net | Date: | Mon, 11 Feb 2013 05:17:36 +0000 |
| Subject: | note 49997 deleted from language.variables by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-193591@lists.php.net to get a copy of this message | ||
Note Submitter: lucas dot karisny at linuxmail dot org
----
Here's a function to get the name of a given variable. Explanation and examples below.
<?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;
}
?>
Explanation:
The problem with figuring out what value is what key in that variables scope is that several
variables might have the same value. To remedy this, the variable is passed by reference and its
value is then modified to a random value to make sure there will be a unique match. Then we loop
through the scope the variable is contained in and when there is a match of our modified value, we
can grab the correct key.
Examples:
1. Use of a variable contained in the global scope (default):
<?php
$my_global_variable = "My global string.";
echo vname($my_global_variable); // Outputs: my_global_variable
?>
2. Use of a local variable:
<?php
function my_local_func()
{
$my_local_variable = "My local string.";
return vname($my_local_variable, get_defined_vars());
}
echo my_local_func(); // Outputs: my_local_variable
?>
3. Use of an object property:
<?php
class myclass
{
public function __constructor()
{
$this->my_object_property = "My object property string.";
}
}
$obj = new myclass;
echo vname($obj->my_object_property, $obj); // Outputs: my_object_property
?>