3

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();
0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.