views:

42

answers:

3

Why this code doesn't work?

public function get($key) {
    return isset($_SESSION[$key]) ? &$_SESSION[$key] : false;
}

Error

Parse error: syntax error, unexpected '&' in C:\Arquivos de programas\EasyPHP-5.3.3\www\myphpblog\code\sessionstorage.class.php on line 12

Thank you.

A: 

A ternary operator is really three expressions, e.g. expr1 ? expr2 : expr3;

See the Notes in Returning References:

If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else.

Gordon
A: 

The syntax for returning a reference in PHP is &<function name>(){ return <referece> } Also, Only variable references should be returned by reference

So, you should probably rewrite it:

function &get($key) {
    $a = false;
    if( isset($_SESSION[$key]) )
        return $_SESSION[ $key ];
    return $a;
}
Christopher W. Allen-Poole
That's... interesting. I've no real idea what returning a reference to a local variable will do in PHP, as I've never tried it. In most other languages it's a serious logic error.
meagar
A: 

Just remove the & and it will work. Dah...

Dmitri