Conceptual question about SESSION variable names defined using a another variable

Discussion in 'PHP' started by horizon22, Sep 24, 2012.

  1. #1
    OK friends, the situation is not so bad, my script works, but I am here just to be clear on the concept since I could not find the information elsewhere. So, all ya enlightened ones, please help me with this :

    //usually defined session variable
    $_SESSION['my_variable'] = "this is my variable";

    //session variable definition with a prefix
    $prefix = "my_";
    $_SESSION[$prefix.'variable'] = "this is my variable";

    In both cases, when you output the session variable name, you get "my_variable". But I wonder what is that requirement of a session variable name being "must" enclosed inside single quotes. This second example technically breaks that rule, does not it? I still get the same variable session name when I look for it..

    Can anyone explain this phenomenon?

    Many thanks.
     
    Solved! View solution.
    horizon22, Sep 24, 2012 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    Both examples are correct. The value between [] is concatenated and then applied as the variable name. You could use double quotes as well and will receive the same result. This is the way it's supposed to work though. You can do the same if you have dynamic variable names, but you would typically need {} in that case.

    Example:

    $some_dynamic_name = 'Hello';
    
    $variable = 'some_dynamic_name';
    
    echo ${$variable}; //Hello
    PHP:
    This example is pretty useless, but there are a lot of cases where dynamic variable name come in handy.
     
    jestep, Sep 25, 2012 IP
  3. horizon22

    horizon22 Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Are you saying that after concatenation, the session automatically becomes like $_SESSION['my_variable']. That is, it value of variable name post concatenation is pulled automatically inside single quotes? Because otherwise the concatenation is not supposed to work like that. No?
     
    horizon22, Sep 25, 2012 IP
  4. #4
    It's not pulled into the quotes, but it's evaluated as a single value which would be the same value as the string in single quotes without being concatenated

    'my_variable' = my_variable;

    'my_'.'variable' = my_variable;

    $prefix = 'my_';
    $prefix.'variable' = my_variable;

    These would all result in the same value regardless of whether they're calling a session variable or not. The $_SESSION array doesn't care whether there are single, double, or no quotes. It only cares what the key is.
     
    jestep, Sep 25, 2012 IP
  5. horizon22

    horizon22 Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks jestep!!
     
    horizon22, Sep 25, 2012 IP