PHP中可以有带空格的变量吗? [英] Can you have variables with spaces in PHP?
问题描述
我在 PHP 中搞乱了变量变量,所以我想出了代码:
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
我只是想了解如果我们有一个带空格的字符串,PHP 将如何表现,并尝试从中创建一个变量变量.似乎它仍然用空格存储变量,因为我做了 var_dump($GLOBALS);
并且我有这个:
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)
我可以通过 $GLOBALS['two words']
访问 'two words' 变量,这里出现了两个问题:
I can access the 'two words' variable through $GLOBALS['two words']
where two questions arise:
- 我可以通过
$
以某种方式直接访问它吗?我在某处读到你需要将整个变量放在大括号中({$two words}
或者我假设${two words}
),但这没有工作. 你真的可以在 PHP 中使用带空格的变量吗?我尝试使用包含空格的键创建一个关联数组,并且可以正常工作:
- 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
推荐答案
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.
这样做:
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.
这篇关于PHP中可以有带空格的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!