问题
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