简体   繁体   English

将SESSION变量存储为常量

[英]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(). 显然,我可以在每个包含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 谢谢,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: index.php文件:

<?php

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

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

?>

config.php: 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!) (我将使用会话本身或使用会话值创建类,因为如果值更改,您会怎么做?您无法覆盖常量!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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