In PHP, all variables are stored in the hasttable structure of the symbol table, and the scope of the symbols is associated with the active symbol table. Therefore, at the same time, there is only one active symbol table.
We want to get to the current active symbol table can be obtained by Get_defined_vars method.
Get_defined_vars//Returns an array of all defined variables
Find the variable name based on the value of the variable, but note that a variable with the same value might exist.
Therefore, the value of the current variable is first saved to a temporary variable, and then the original variable is assigned a unique value to find out the name of the variable, and after the name is found, the value of the temporary variable is assigned to the original variable.
Example 1:
<?php
$a = ' m ';
Echo ' $a name is: '. Get_variable_name ($a). ' Value: '. $a; $a name is:a value:100
/**
* @param String $var the variable to find
* @param Array $scope the range to search for
* @param String variable name
*
/function Get_variable_name (& $var, $scope =null) {
$scope = $scope ==null? $ GLOBALS: $scope; If there is no scope to find in Globals
//Because there may be a variable of the same value, therefore, the value of the current variable is saved to a temporary variable, and then the original variable is assigned a unique value to find out the name of the variable, and after the name is found, the value of the temporary variable is assigned back to the original variable
$tmp = $var;
$var = ' Tmp_value_ '. Mt_rand ();
$name = Array_search ($var, $scope, true); Find variable names based on value
$var = $tmp;
return $name;
>
Example 2: Get the variable name defined inside the function
<?php
function Test () {
$a = ' m ';
Echo ' $a name is: '. Get_variable_name ($a);
}
Test (); $a name is:undefined
//Because the variable globals defined in the function will not find
function test2 () {
$a = ' m ';
Echo ' $a name is: '. Get_variable_name ($a, get_defined_vars ());
Test2 (); $a name is:a
//Set scope to Get_defined_vars () to find
?>
Author: csdn blog proud Snow star Maple
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/PHP/