php Method to get the name of a variable

  • 2021-07-18 07:24:04
  • OfStack

In PHP, all variables are stored in the HastTable structure of "symbol table", and the scope of symbols is associated with the active symbol table. Therefore, there is only one active symbol table in the same time.

We want to get the current active symbol table, which can be obtained by get_defined_vars method.

get_defined_vars//Returns an array of all defined variables

Find variable names based on their values, but be aware that there may be variables with the same value.

Therefore, the value of the current variable is saved to a temporary variable first, and then the original variable is assigned only 1 value, so as to find out the name of the variable. After finding the name, the value of the temporary variable is re-assigned to the original variable.

Example 1:


<?php 

$a = '100'; 

echo '$a name is:'.get_variable_name($a).' value:'.$a; // $a name is: a value: 100 

/** 
* @param String $var  Variable to find  
* @param Array $scope  Scope to search  
* @param String  Variable name  
*/ 
function get_variable_name(&$var, $scope=null){ 

$scope = $scope==null? $GLOBALS : $scope; //  If there is no scope, the globals Seek in  

//  Because it is possible to have variables with the same value , Therefore, the value of the current variable is saved to the 1 Of the temporary variables , Then the original variable is assigned only 1 Value , To find out the name of the variable , After finding the name, , Re-assign the value of a temporary variable to the original variable  
$tmp = $var; 

$var = 'tmp_value_'.mt_rand(); 
$name = array_search($var, $scope, true); //  Find variable names by value  

$var = $tmp; 
return $name; 
}
?>

Example 2: Get the variable name defined in function


<?php 
function test(){ 
$a = '100'; 
echo '$a name is:'.get_variable_name($a); 
} 

test(); // $a name is: undefined 
// Because in function Variables defined in globals Will not be found  

function test2(){ 
$a = '100'; 
echo '$a name is:'.get_variable_name($a, get_defined_vars()); 
} 

test2(); // $a name is: a 
//  Will scope Set to  get_defined_vars()  Can be found  

?>

Related articles: