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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2003036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:37:48  来源:igfitidea点击:

PHP: Using spaces in associative array indices

phpassociative-array

提问by Nick Heiner

Is this bad practice/can cause problems?

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

$_SESSION['stuff to keep']

As opposed to calling str_replace()on the indices.

与调用str_replace()索引相反。

回答by Victor Nicollet

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:

在这里,您的代码无声无息地行为不端,并且可能需要一段时间才能找到错误。好的做法是使用 PHP 强制的名称,例如类常量:

$_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 objectwon't work anymore, but you shouldn't be doing that anyway with your session.

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

Allowing user-entered text into session keys is, of course, a blatant security fault.

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

回答by Pascal MARTIN

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 extractfunctions, 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.

extract不过,如果您正在使用这些功能,这可能会导致某种问题。如果它创建名称中带有空格的变量(不知道是否会),则访问您的变量将很困难(但并非不可能)

回答by Adam Hopkinson

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

它不会导致问题,但数组键通常被视为变量名,因此应该以相同的考虑选择

回答by BenTheDesigner

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.

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