Can you have variables with spaces in PHP?

故事扮演 提交于 2019-12-24 14:29:47

问题


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:


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.



来源:https://stackoverflow.com/questions/29792444/can-you-have-variables-with-spaces-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!