すべての朝の検索の後、私はこの解決策を見つけました:
/**
* 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>';
}
変数名を取得するには、次のvardump()
ように使用する必要があります。
vardump($variable_name, get_defined_vars());
get_defined_vars()
この関数は、get_defined_vars() が呼び出されたスコープ内で、環境変数、サーバー定義変数、ユーザー定義変数など、すべての定義済み変数のリストを含む多次元配列を返します。
コードについてさらに説明を加えます。コードにはいくつかのエキゾチックな関数が使用されています。
/**
* 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));
$_var
値の配列$aDefinedVars_0
を変更したため、値$aDefinedVars
のみを除いて同一です(変数への参照を使用しないことに$_var
注意してください。変更には影響しませんでした)。$aDefinedVars_0
$_var
$aDefinedVars_0
これで、array_diff_assoc
関数は (元の$aDefinedVars_0
値で) と$aDefinedVars
(変更された$_var
値で) を比較し、連想配列 (位置$_var
の名前と$_var
値を 1 つだけ含む配列) との差を返します。
このarray_keys
関数は、入力配列から数値と文字列のキーを返します (入力配列には、探している位置が 1 つだけ含まれています)。
$_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。私の英語でごめんなさい。