What's the proper term for converting a string into a variable/class/method?
I know it sounds so dumb but people were aski开发者_高级运维ng me about it and I don't have a proper answer.
Like
$var = "var1";
$var1 = "hello";
echo $$var;
Thanks!
You are talking about Variable variables :)
They're called variable variables.
It can be called "wrong program design" and "time to learn arrays"
The mechanism to specify a variable by using the value of another variable is called variable variables.
This might seem cool is some way. But I rather think that it’s an obscure technique and can also tempt to use some dangerous pattern like exporting input values to the global variable space (just like register globals does).
There are also some restrictions with variable variables:
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable
$this
is also a special variable that cannot be referenced dynamically.
This basically describes that the following is not possible:
$name = '_GET'; // identifier of the superglobal $_GET
$args = $$name;
But there’s also a workaround for this by using the $GLOBALS
array:
$name = '_GET';
$args = $GLOBALS[$name];
精彩评论