I'm trying to learn OOP in PHP and I'm making a class with static methods.I tried the code below but the session_start(); will not work because the methods are static and no object is getting instantiated.Do you know any solution to this problem?
<?php
class Session{
public function __construct(){
session_start();
}
public static function set($data){
foreach ($data as $key => $value) {
$_SESSION[$key] = $value;
}
}
public static function get($key){
return $_SESSION[$key];
}
}
Session::set(array(
'mySessionKey' => 'mySessionValue'
));
I would really recommend you to add this to the top of the files where you operate with sessions:
if(session_status() == PHP_SESSION_NONE) session_start();
This starts your session if it did not already start.
Go to the php.net documentation to learn more about the super global $_SESSION
.
Hope this helps.
Slight change to @Bluedayz answer ...
<?php
class Session {
public static function set($data) {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
foreach ($data as $key => $value) {
$_SESSION[$key] = $value;
}
}
public static function get($key) {
return $_SESSION[$key];
}
}
Session::set(array(
'mySessionKey' => 'mySessionValue'
));
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.