PHP:在关联数组索引中使用空格
这是不好的做法/会导致问题吗?
$_SESSION['stuff to keep']
与在索引上调用 str_replace()
相反。
Is this bad practice/can cause problems?
$_SESSION['stuff to keep']
As opposed to calling str_replace()
on the indices.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是不好的做法,但不是因为空间。
在这里,您的代码默默地出现了错误,并且可能需要一段时间才能发现该错误。好的做法是使用 PHP 强制的名称,例如类常量:
然后您可以将该常量定义为您认为有趣或可读的任何常量,例如
"stuff to keep"
(带空格) 。当然,extract()
和转换为object
将不再起作用,但无论如何您都不应该在会话中这样做。当然,允许用户在会话密钥中输入文本是一个明显的安全错误。
This is bad practice, but not because of the space.
Here, your code is silently misbehaving, and the bug can take a while to be found. Good practice is to use a PHP-enforced name, such as a class constant:
You may then define that constant to any constant you find interesting or readable, such as
"stuff to keep"
(with spaces). Of course,extract()
and casting toobject
won't work anymore, but you shouldn't be doing that anyway with your session.Allowing user-entered text into session keys is, of course, a blatant security fault.
你可以做到这一点,它会起作用——即使当我“手动”设置数组的键时我通常不会这样做,但当我从文件 获取键时有时会发生这种情况(对于实例),而且我从来没有遇到过任何问题。
如果您使用
extract
函数,这可能会导致某种问题。如果它创建名称中带有空格的变量(不知道是否会),那么访问您的变量将很困难(但并非不可能)。You can do that, it'll work -- and even if I don't generally do it when I set the keys of my arrays "by hand", it sometimes happens when I get the keys from a file (for instance), and I've never had any problem with this.
Maybe this could cause some kind of a problem if you are using the
extract
functions, though. If it creates variables with spaces in their names (don't know if it will) it'll be difficult (but not impossible) to access your variables.它不会引起问题,但数组键通常被视为变量名,因此应以相同的考虑因素进行选择
It won't cause a problem, but array keys are usually considered like variable names so should be chosen with the same considerations
在我看来,似乎添加了不必要的空格...我通常不使用空格。不过,如果这样做,请确保引用数组键。
Seems like adding unnecessary whitespace in my opinion... I don't usually use spaces. If you do, though, make sure you quote the array keys.