Access Session Variable within a class

时光总嘲笑我的痴心妄想 提交于 2020-01-02 08:03:07

问题


Is it considered normal using session_start on a class constructor when session values need to be retrieved or keep? Best practices?

Session variable coudn't be retrieved from class unless session_start is called from __contruct.

session_start();    

if(isset($_REQUEST['siteid'])){
    $siteid = $_REQUEST['siteid'];
    $_SESSION['siteid'] = $siteid;
    echo $siteid;
}else{
    $siteid = "";
}
require_once 'common/lib_constant.php';
require_once 'common/database.php';
require_once 'common/common.class.php';
$commonClass = new commonClass();

回答1:


best practice is to start session from the bootstrap.
and session itself accessing through some kind of a smart wrapper class (see ZF for examples).
That way you should be 100% sure you won't have header problems and duplicate session_start calls in your code.
A class can be instantiated many times/request...bootstrap runs only once/request.




回答2:


You should use a wrapper object to access session variables, that calls session_start() on the first request it handles, and then saves a flag meaning that this has been done, or it calls session_start() simply within its constructor.

You can use the singleton pattern or the so-called dependency injection which is, despite the original name, just passing a reference to a (call it) $Session object to every object that needs it.

There should exist only one instance of the Session object.



来源:https://stackoverflow.com/questions/5874976/access-session-variable-within-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!