Can you have variables with spaces in PHP?

2019-08-11 06:06发布

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:

  1. 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.
  2. 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
    

1条回答
倾城 Initia
2楼-- · 2019-08-11 06:46
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.

查看更多
登录 后发表回答