Explain this interview question to me...
Q: If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?
A: 100, it’s a reference to existing variable.
Explain this interview question to me...
Q: If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?
A: 100, it’s a reference to existing variable.
That's a variable variable. PHP will look up the variable with the name stored in the string $b
. So if $b == 'a'
then $$b == $a
.
It's a lot like pointers in C, except they use variable name strings instead of memory addresses to point to each other. And you can dereference as many times as you want:
$a = 5;
foreach (range('b', 'z') as $L) {
$$L = chr(ord($L) - 1);
}
echo $$$$$$$$$$$$$$$$$$$$$$$$$$z;
Output:
5
I don't know if the '?' is erroneous in the statement '$$b? - 100' but I don't think that will compile.
However:
$a = 5
$b = 'a';
$c = $$b - 100;
$c will equal -95, because $$b is a variable variable reference and given that $a = 5 it resolves to $a (5) - 100, or -95.
-95
is the answer as if u will echo $b
u will get output as
"a
"
and if u echo $a
u will get out but as "5
"
hence in this sense when u $(echo $b)
which same as $(a)
hence u will get it as "5-100
" which is "-95
"