Log in

View Full Version : Any way to shorten session variable names?



Schmoopy
02-03-2009, 12:37 AM
Ok, I've just started looking into sessions and was messing around with simple stuff, like incrementing the user's session value every time they requested the page, but I came across the following problem:

I was trying to do the following



session_start();

session_register('counter');

$counter = $_SESSION['counter'];

// Try incrementing $counter now that it points to the session variable

$counter++;

echo $counter;



It quickly became apparent that the value of the counter only reflected the value of the session variable, meaning I can't increment the counter variable.

The way to do it would be:



$_SESSION['counter']++;


So I was just wondering if there was a way of transferring the value to the $counter variable, instead of merely reflecting what is held in the session.

In its current state I can only echo the $counter, but I can't add anything to it, or perform any operations on it.

Any way to get around this?

Thanks,

Jack.

Twey
02-03-2009, 06:35 AM
session_register (http://www.php.net/session-register)() and $_SESSION are alternatives, and not to be used together. session_register() requires register_globals, and is therefore deprecated. Just use $_SESSION.

To answer your question: you can make a reference (http://www.php.net/manual/en/language.references.php) to the entry and modify that:
<?php
session_start();

$c =& $_SESSION['counter'];
++$c;
?>Or, alternatively, make a copy then save it back:
<?php
session_start();

$c = $_SESSION['counter'];
++$c;
$_SESSION['counter'] = $c;
?>Of course, for such a use case as this it is pointless. This particular instance actually isn't that long; I suggest you try typing lessons (and stay far away from Java, famed for its verbose identifiers :)).

Schmoopy
02-03-2009, 12:02 PM
Ah I see, thanks for that :)