After all morning search I've found this solution:
/**
* Functions that will display name of the variable, and it's value, and type
*
* @param type $_var - variable to check
* @param type $aDefinedVars - Always define it this way: get_defined_vars()
* @return type
*/
function vardump(&$_var, &$aDefinedVars = null){
if($aDefinedVars){
foreach ($aDefinedVars as $k=>$v)
$aDefinedVars_0[$k] = $v;
$iVarSave = $_var; // now I copy the $_var value to ano
$_var = md5(time());
$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
$_var = $iVarSave;
$name = $aDiffKeys[0];
}else{
$name = 'variable';
}
echo '<pre>';
echo $name . ': ';
var_dump($_var);
echo '</pre>';
}
To get the variable name You have to be sure to use vardump()
like below:
vardump($variable_name, get_defined_vars());
get_defined_vars()
This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.
I'll put some more explanation for the code, there are some exotic functions used in it.
/**
* Functions that will display name of the variable, and it's value, and type
*
* @param type $_var - variable to check
* @param type $aDefinedVars - Always define it this way: get_defined_vars()
* @return type
*/
function vardump(&$_var, &$aDefinedVars = null){
// $aDefinedVars - is array of all defined variables - thanks to get_defined_vars() function
if($aDefinedVars){
// loop below is used to make a copy of the table of all defined variables
foreach ($aDefinedVars as $k=>$v)
$aDefinedVars_0[$k] = $v; // this is done like that to remove all references to the variables
$iVarSave = $_var; // now I copy the $_var value to another variable to prevent loosing it
$_var = md5(time()); // completly random value
// and the most tricky line
$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
Becouse I have change the $_var
value array $aDefinedVars_0
and $aDefinedVars
are identical except only $_var
value(NOTE $aDefinedVars_0
don't use reference to the variables so chengin $_var
I didn't affect on $aDefinedVars_0
).
Now the array_diff_assoc
function compares $aDefinedVars_0
(with oryginal values) against $aDefinedVars
(with changed $_var
value) and returns the difference with is associative array (array that contains only one position $_var
name and $_var
value).
The array_keys
function returns the keys, numeric and string, from the input array (and input array contains only one position the one that I'm looking for).
$_var = $iVarSave; // now I can restore old $_var value
$name = $aDiffKeys[0]; // name of the $_var is on the first (and the only position) in the $aDiffKeys array
}else{ // is someone won't use get_defined_vars()
$name = 'variable';
}
echo '<pre>';
echo $name . ': ';
var_dump($_var); // it can be changed by print_r($_var);
echo '</pre>';
}
PS. I'm sorry for my English.