PHP to get variable names of variables in a section of code bug analysis _php Tips

Source: Internet
Author: User
Copy Code code as follows:

/**
* Get variable name
*
* @param $string
* @return $string
*
* $test = "Helo";
* $test 2 = "Helo";
* Getvarname ($test 2);
*/
Function Getvarname (& $SRC) {
Store current Variable Value
$save = $SRC;
Store all variable values
$allvar = $GLOBALS;
Do not traverse $globals in a function, there will be a stack problem
foreach ($allvar as $k => $v) {
Variable values are the same, 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 the $globals[$k] then change, that is the same variable.
if ($src = = $GLOBALS [$k]) {
echo "\$ $k name is $k
";
Restore variable values
$SRC = $save;
return $k;
}
}
}
}

Copy down after found this how to test results sometimes wrong, think for a long time, finally understand, although very simple, but they are still recorded, hope to encounter the same situation students attention.
For example: Now I'm testing
Copy Code code as follows:

$test 2 = "Hello";
$countNum = 0;
Echo Getvarname ($test 2);
According to the principle should be output as "test2", but the output is "Countnum",

Because in the function of the
if ($src = = $v) There are problems such as $src= "Hello", $GLOBALS there is a variable $countnum=0;
At this time in the loop to determine if ($src = = $v), that is, "Hello" ==0, the result of the comparison is true, type conversion when "hello" to plastic to 0,
Then you exit the loop and get the wrong result.
One solution is if ($src = = $v) change to if ($src = = = $v), that is, identity.
If I understand you wrong, please correct me and make progress together.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.