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
alexwlchan
5,2325 gold badges35 silver badges46 bronze badges
asked Apr 22, 2015 at 8:56
6
echo "$two words"; // error since $two doesn't exist
The issue with this is that the string interpolation rules will stop at the first character that's not valid in a variable name. It is not specific to variable variables as such, it's specific to string interpolation.
This'll do:
echo ${'two words'};
But since this is rather awkward and doesn't work in all the same situations as valid variable names do [e.g. string interpolation], you really shouldn't do this ever.
answered Apr 22, 2015 at 9:04
deceze♦deceze
497k81 gold badges719 silver badges867 bronze badges
I just found out a very strange PHP feature by browsing the PHP-GTK2 API with the Reflection classes : spaces can be used in some alien places, like variable names. Well, try this in PHP 5.2.5, for instance: The case with constants
is better known, being mentioned on php.net : Stranger is the fact that you are not allowed to use that same syntax on parameter names, class constants, or class properties: in every case, the syntax fails. So how does this related to PHP-GTK2 ? Actually, I discovered this possibility about spaces in variable names because the Reflection API shows There's a bit
of magic in ext/gtk+/gdk.overrides regarding these parameters [starting line 312 in version 1.81], because this is not the default Gdk format. However, at any rate, it seems that this syntax is not allowable from PHP source, even though the PHP-GTK extension uses it.But the doc says you can't !
Spaces in PHP variable names
Spaces in PHP constant names
Spaces in other PHP names
Spaces in PHP-GTK names
GdkColorMap::alloc_color[]
like this: Method [ public method alloc_color ] {
- Parameters [3] {
Parameter #0 [ $color OR red ]
Parameter #1 [ $blue ]
Parameter #2 [ $green ]
}
}