Magic methods in static objects

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

$_SESSION['foo'] = $bar; 

I'm doing it:

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

and the set function will do something like this:

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

Ok, this works, but I would like to use it like this:

 Session['foo'] = $bar 

or like this:

 Session->foo = $bar 

I found that I cannot use → in static objects, and I also cannot use magic functions such as __set and __get. So, is there a way I can achieve this behavior?

+4
source share
2 answers

Make your session class single?

 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 this:

 echo(Session::$instance->foo); 
+3
source

You should use __call, then

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

But Session['foo'] = $bar cannot be used.

0
source

Source: https://habr.com/ru/post/1386532/


All Articles