1

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'
));
user3407278
  • 1,233
  • 5
  • 16
  • 32
  • 1
    This is the wrong way to manage your session. Each individual method shouldn't trigger a `session_start` call; your program should be organized so that the session is guaranteed to have started before any of these methods can be called. – user229044 Aug 31 '14 at 14:00

2 Answers2

0

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.

Bluedayz
  • 599
  • 5
  • 17
0

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'
));
Mark Tomlin
  • 8,593
  • 11
  • 57
  • 72
  • Does this actually make any difference? – Bluedayz Aug 31 '14 at 13:58
  • thanks but is there any __construct like method for using with static methods?I mean I want the session_start(); to run before calling any of the static methods,is that possible? – user3407278 Aug 31 '14 at 14:00
  • Namely, code encapsulation, and keeps it in spec for what the OP wanted. – Mark Tomlin Aug 31 '14 at 14:00
  • @user3407278 There is no way to do it for static methods. If you put it into a file though, you can simply add a `Session::init()` call to the bottom of where you create your Session class, and just require it once. Alternately, use a singleton pattern. – h2ooooooo Aug 31 '14 at 14:01
  • @user3407278, negative, `__constructors` are only called when you assign a variable that classes instantiation. [See the answer here.](http://stackoverflow.com/questions/8231198/php-constructors-and-static-functions) – Mark Tomlin Aug 31 '14 at 14:05