vote up 1 vote down star

Is this bad practice/can cause problems?

$_SESSION['stuff to keep']

As opposed to calling str_replace() on the indices.

flag

72% accept rate

5 Answers

vote up 3 vote down check

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.

link|flag
vote up 1 vote down

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

link|flag
vote up 1 vote down

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.

link|flag
+1 Good point - extract will throw an error (warning?) if it is asked to extract an array that has invalidly named keys – adam Jan 4 at 23:36
vote up 0 vote down

Bad practice... Well, I don't do that - but that is just a preference. It is, however, completely legitimate.

Cause problems... I don't see anything that would implicitly cause a problem with using spaces in a key.

link|flag
vote up 0 vote down

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.

link|flag

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.