PHP:在关联数组索引中使用空格

发布于 2024-08-16 18:49:31 字数 122 浏览 3 评论 0原文

这是不好的做法/会导致问题吗?

$_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

素手挽清风 2024-08-23 18:49:31

这是不好的做法,但不是因为空间。

// file foo.php
$_SESSION['stuff to keep'] = 42;

// file bar.php
if ($_SESSION['stufft o keep'] == 42) frobnicate();

在这里,您的代码默默地出现了错误,并且可能需要一段时间才能发现该错误。好的做法是使用 PHP 强制的名称,例如类常量:

$_SESSION[Stuff::TO_KEEP] = 42;

if($_SESSION[Stuff::TOO_KEEP] == 42) 
// error: no constant TOO_KEEP in class Stuff

然后您可以将该常量定义为您认为有趣或可读的任何常量,例如 "stuff to keep" (带空格) 。当然,extract() 和转换为 object 将不再起作用,但无论如何您都不应该在会话中这样做。

当然,允许用户在会话密钥中输入文本是一个明显的安全错误。

This is bad practice, but not because of the space.

// file foo.php
$_SESSION['stuff to keep'] = 42;

// file bar.php
if ($_SESSION['stufft o keep'] == 42) frobnicate();

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:

$_SESSION[Stuff::TO_KEEP] = 42;

if($_SESSION[Stuff::TOO_KEEP] == 42) 
// error: no constant TOO_KEEP in class Stuff

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 to object 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.

铁轨上的流浪者 2024-08-23 18:49:31

你可以做到这一点,它会起作用——即使当我“手动”设置数组的键时我通常不会这样做,但当我从文件 获取键时有时会发生这种情况(对于实例),而且我从来没有遇到过任何问题。

如果您使用 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.

魔法唧唧 2024-08-23 18:49:31

它不会引起问题,但数组键通常被视为变量名,因此应以相同的考虑因素进行选择

It won't cause a problem, but array keys are usually considered like variable names so should be chosen with the same considerations

若水般的淡然安静女子 2024-08-23 18:49:31

在我看来,似乎添加了不必要的空格...我通常不使用空格。不过,如果这样做,请确保引用数组键。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文