Re: Accessing $_SESSION variables in PHP5 needs isset() first?

From: Chung Leong (chernyshevsky_at_hotmail.com)
Date: 07/28/04


Date: Tue, 27 Jul 2004 23:52:33 -0400


"Pedro Fonseca" <nospam@pedrofonseca.com> wrote in message
news:15109a72.0407271424.7eb2874b@posting.google.com...
> The only way I can think of to get around this (without, of course,
> turning Notices off in the php.ini) is to first use isset on the
> session variable, like this:
>
> if ( isset($_SESSION['foo']) && $_SESSION['foo'] == 'Bar' ) {
> $value = 5;
> }
>
> Is this really necessary? Or is there any other way of doing this in
> PHP5? IMHO the whole point of session variables is that they don't
> really have to be defined in one particular script, so why that
> NOTICE?... Do I really need the superfluous call to isset()?

One thing you can do with PHP5 is wrap $_SESSION in an object and access the
element as properties:

class DataObject {
    private $values;
    function __construct($values, $default = array()) {
        $this->values = array_merge($default, $values);
    }
    function __get($name) {
        return isset($this->values[$name]) ? $this->values[$name] : null;
    }
}

$Session = new DataObject($_SESSION);

if($Session->foo == 'bar') {
    ...
}

Property access is one of the neatest features of PHP5. Has the potential of
majorly decluttering your code. In an expanded version of the class above,
for example, I have the get function automatically escaping the property
value based on a suffix. $Post->foo_html would be
htmlspecialchars($_POST['foo']), $Post->foo_sql would be
mysql_escape_string($_POST['foo']), etc.

Unfortunately it seems to be one of the buggier features. My code blew up
when I had an array in there :-(



Relevant Pages

  • Re: Accessing $_SESSION variables in PHP5 needs isset() first?
    ... Until PHP5 I was using session variables like: ... you need to use isset everywhere. ... PHP DB Edit Toolkit -- PHP scripts for building ...
    (comp.lang.php)
  • Accessing $_SESSION variables in PHP5 needs isset() first?
    ... I'm porting everything to PHP5. ... Until PHP5 I was using session variables like: ... generates a NOTICE error: ... Do I really need the superfluous call to isset()? ...
    (comp.lang.php)
  • Re: PHP5 and Global Array ($_GET)
    ... there were no query string parameters passed like script.php?foo=bar ... down and hammer out code for PHP5 given its still beta. ... use isset() on a variable if its supplied in _GET/_POST/_COOKIE to make ... PHP is still a young language and continues to evolve. ...
    (comp.lang.php)