Copy codeThe Code is as follows:
/**
* Get the variable name
*
* @ Param $ string
* @ Return $ string
*
* $ Test = "helo ";
* $ Test2 = "helo ";
* GetVarName ($ test2 );
*/
Function getVarName (& $ src ){
// Store the current variable value
$ Save = $ src;
// Store all variable values
$ Allvar = $ GLOBALS;
// Do not directly traverse $ GLOBALS in the function, and stack problems may occur.
Foreach ($ allvar as $ k => $ v ){
// The variable values are the same and may not be the same variable, because the values of multiple variables may be the same
If ($ src = $ v ){
// Change the value of the current variable $ src
$ Src = 'change ';
// If $ GLOBALS [$ k] also changes, it is the same variable.
If ($ src = $ GLOBALS [$ k]) {
// Echo "\ $ k name is $ k
";
// Restore the variable value
$ Src = $ save;
Return $ k;
}
}
}
}
After copying it, I found out how to test the result. Sometimes it's wrong. After thinking for a long time, I finally figured it out. Although it's very simple, I still keep a record, and I hope you will pay attention to it in the same situation.
For example, now I test
Copy codeThe Code is as follows:
$ Test2 = "hello ";
$ CountNum = 0;
Echo getVarName ($ test2 );
// The output is test2, but the output is countNum ",
Because
If ($ src = $ v) there is a problem here, for example, $ src = "hello", $ GLOBALS contains a variable $ countNUm = 0;
In this case, when looping, judge if ($ src = $ v), that is, "hello" = 0, and the comparison result is true, during type conversion, "hello" is converted into an integer of 0,
Then exit the loop and get the wrong result.
One solution is to change if ($ src = $ v) to if ($ src = $ v), that is, constant.
If I understand it wrong, please correct it and make progress together.