I was messing around with variable variables in PHP, so I came up with the code:
$a = 'two words';
$$a = 'something';
echo $$a; // outputs something
echo "$two words"; // error since $two doesn't exist
I was just trying to understand how PHP will behave if we have a string with spaces, and try to make a variable variable from it. And it seems it still stores the variable with spaces, since I did var_dump($GLOBALS);
and I have this:
'a' => string 'two words' (length=9)
'two words' => string 'something' (length=9)
I can access the 'two words' variable through $GLOBALS['two words']
where two questions arise:
- Can I somehow access it directly with the
$
? I've read somewhere that you need to get the whole variable in curly brackets ({$two words}
or I assume${two words}
), but that didn't work. Can you actually have variables with spaces in PHP? I tried making an associative array with keys that contain spaces and that worked:
$a['a space'] = 1; echo $a['a space']; // 1