note 88074 rejected from language.variables by rbowen
| From: | rbowen@php.net | Date: | Tue, 06 Apr 2010 17:15:25 +0000 |
| Subject: | note 88074 rejected from language.variables by rbowen | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-167735@lists.php.net to get a copy of this message | ||
Note Submitter: mccarre at uwindsor dot canada
----
I needed a form of refelction for my work that still uses 4.2.0 that gets a variables name in
context with the application.
For example
[code]class someclass{
var $field1
function getFieldsName(){
print getVarName($this->field1);
}
}
myObject = new someclass();
myObject->getFieldsName();
//This will return "myObject->field1".
[/code]
If you want to change the format you can do so with the code, my code isn't fully complete for
features, but it does the basics of what is necessary for getting a variables name and it's
owners.
[code]
function getVarName(&$var)
{
$old = $var; //store the value of the var so we don't lose it.
$var = "__random__" . rand() . "temp"; //assign a random string to distinguish
this var from others.
//search for the random string to find the variable in $GLOBALS
//Note: this is an iterative deepening depth first search.
$key = IDDF_search(array_reverse($GLOBALS), $var); //we reverse the global array first to make it
faster,
//because variables appear at the bottom of hte globals array list.
$var = $old;
return $key;
}
function IDDF_search($array, $var, $depth=100)
{
for($i=0; $i<$depth; $i++)
if($temp = RestrictedDF_search($array, $var, $i))
return $temp;
}
function RestrictedDF_search($array, $var, $depth=100, $inArray=false)
{
if($depth < 0) //we've gone to our maximum depth, so return.
return false;
$depth--;
$possibleCloseBracket = ($inArray) ? "]" : "";
foreach($array as $key => $value) {
if(is_string($value) && $value === $var)
return $key . $possibleCloseBracket;
//else
//print $key . ": the value != " . $var . "<br />";
if(is_array($value))
if($temp = RestrictedDF_search($value, $var, $depth, true))
return $key . $possibleCloseBracket . "[" . $temp;
//PHP 4.2.0 =)
if(is_object($value))
if($temp = RestrictedDF_search(get_object_vars($value), $var, $depth))
return $key . $possibleCloseBracket . "->" . $temp;
}
return false;
}
[/code]
This was built of a function noted here at an earlier date. I think he actually named his function
getVarName. Mine takes it a step further combining the recursive search defined in the array_search
notes as well, so a user can get the name of a variable no matter where it is in GLOBALS.
If only I had php 5 to work with at work. =P