Question

I am using a magic getter/setter class for my session variables, but I don't see any difference between normal setters and getters.

The code:

class session
{
    public function __set($name, $value)
    {
        $_SESSION[$name] = $value;
    }

    public function __unset($name)
    {
        unset($_SESSION[$name]);
    }

    public function __get($name)
    {
        if(isset($_SESSION[$name]))
        {
            return $_SESSION[$name];
        }
    }
}

Now the first thing I noticed is that I have to call $session->_unset('var_name') to remove the variable, nothing 'magical' about that.

Secondly when I try to use $session->some_var this does not work. I can only get the session variable using $_SESSION['some_var'].

I have looked at the PHP manual but the functions look the same as mine.

Am I doing something wrong, or is there not really anything magic about these functions.

Was it helpful?

Solution

First issue, when you call

unset($session->var_name);

It should be the same as calling

$session->_unset('var_name');

Regarding not being able to use __get(); What doesn't work? What does the variable get set to and what warnings are given. Ensure you have set error_reporting() to E_ALL.

It may also be a good idea to check you have called session_start

OTHER TIPS

I thought getters and setters were for variables inside the class?

class SomeClass {
    private $someProperty;

    function __get($name) {
        if($name == 'someProperty') return $this->someProperty;
    }

    function __set($name, $value) {
        if($name == 'someProperty') $this->someProperty = $value;

    }
}


$someClass = new SomeClass();
$someClass->someProperty = 'value';
echo $someClass->someProperty;

?

class session { /* ...as posted in the question ... */ }

session_start();
$s = new session;
$s->foo = 123;
$s->bar = 456;
print_r($_SESSION);

unset($s->bar);
print_r($_SESSION);

prints

Array
(
    [foo] => 123
    [bar] => 456
)
Array
(
    [foo] => 123
)

Ok, maybe not "magical". But works as intended.
If that's not what you want please elaborate...

This is my understanding till now about magic function

Please correct me if i am wrong...

$SESSION is an array and not an Object therefore you can access them using $session['field'] and not $session->field

magic Function allow you to use the function name __fnName before any function as

fnNameNewField($value);

so ,it will be separated into NewField as key and will be sent to __fnName and oprations will be done on this

eg: setNewId($value) will be sent to __set() with key= new_id and Parameters...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top