Advanced Search

Results 1 to 3 of 3

Thread: Any way to shorten session variable names?

  1. #1
    Join Date
    Sep 2008
    Location
    Bristol - UK
    Posts
    842
    Thanks
    32
    Thanked 132 Times in 131 Posts

    Default Any way to shorten session variable names?

    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

    Code:
    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:

    Code:
    $_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.

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,878
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    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 to the entry and modify that:
    Code:
    <?php
      session_start();
    
      $c =& $_SESSION['counter'];
      ++$c;
    ?>
    Or, alternatively, make a copy then save it back:
    Code:
    <?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 ).
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. #3
    Join Date
    Sep 2008
    Location
    Bristol - UK
    Posts
    842
    Thanks
    32
    Thanked 132 Times in 131 Posts

    Default

    Ah I see, thanks for that

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •