Pirozek
Pirozek

Reputation: 1270

Magic methods in static objects

I am trying to achieve this. I have session manager class, its something I developed for my framework. I need to have unique session keys, so instead of doing something like this:

$_SESSION['foo'] = $bar;

I do this:

Session::set('foo',$bar);

and the set function will do something like this:

$_SESSION[$unique.'foo'] = $bar;

Its nice, it works, but I would like to use it like this:

Session['foo'] = $bar

or like this:

Session->foo = $bar

I found that I cant use -> in static objects, and I also cant use magic functions like __set and __get. So, is there any way how can I achieve this behavior?

Upvotes: 4

Views: 804

Answers (2)

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35146

Make your session class a singleton?

class Session
{
   public static $instance;

   public static function init()
   {
        self::$instance = new Session();
   }    

    public function __get($key)
    {
        return $_SESSION[$key];
    }
}

And then use it like so:

echo(Session::$instance->foo);

Upvotes: 3

Anthony
Anthony

Reputation: 3218

You have to use __call then

http://php.net/manual/en/language.oop5.overloading.php

But Session['foo'] = $bar is impossible to use.

Upvotes: 0

Related Questions