简体   繁体   中英

does session_start have to be called inside every function?

does session_start() have to be called within every function of a class? like:


class User {

  var $username;

  function set_session_username($username) {
    session_start();  # do I really need to call this again?
    $_SESSION['username'] = $username;
  }


  function retrieve_session_username() {
    session_start(); # do I really need to call this again?
    $this -> username = $_SESSION['username'];
  }

}

session_start();

$user = new User();
$user -> set_session_username('savagewood');
$user -> retrieve_session_username();

echo $user -> username;

No, it only needs to be called once per request. So the first script the runs post it at top of that file

No , you need to start the session only once in the page which is loaded. Not in any class or functions.

不,在应用程序发送任何输出之前,应该在应用程序入口点中调用一次session_start()

You could check if session is started:

if (!session_id())
  session_start();

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