简体   繁体   中英

Storing SESSION variables as CONSTANTS

More a general query this than anything else but would be interestEed in hearing what the general consensus might be.

I have user session data stored in a session user array as is usual. Obviously I can access that array directly on each page that includes session_start(). However I'd like to be able to access the session items using simple variables rather than referencing the array each time. Really what it comes down to is less typing for me but also neater code.

I was thinking of including a file at the top of each page that defines each session variable as a constant and then I could reference the constant rather than the array.

Would this work or would it cause issues if more than one user is logged in?

Thanks, G

Yes it would work! But i think that's not a good idea/ it's unnecessary.

As an example that it works:

index.php:

<?php

    session_start();
    $_SESSION['username'] = "myuser1233";

    require_once("config.php");
    echo USERNAME;

?>

config.php:

<?php

    //session_start(); you would have to start the session if you don't start the session in the file which includes this one
    define("USERNAME", $_SESSION['username']);

?>

Output:

myuser1233

(I would use the session itself or make a class with the session values because what do you do if the value change? you can't overwrite a constant!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM