dragonlew9876 2014-07-17 12:20
浏览 92
已采纳

在写上下文中不能使用函数返回值

I have this simple session class

class Session
{
    public static function init() {
       @session_start();
    }

    public static function set($key, $value) {
        $_SESSION[$key] = $value;
    }

    public static function get($key) {
        if (isset($_SESSION[$key]))
            return $_SESSION[$key];
    }

    public static function destroy() {
        unset($_SESSION);
        session_destroy();
    }
}

In my other class I have

public function verifyFormToken($form)
{
    // check if a session is started and a token is transmitted, if not return an error
    if(!isset(Session::get($form.'_token'))){ 
        return false;
    }

    // check if the form is sent with token in it
    if(!isset($data['token'])) {
        return false;
    }

    // compare the tokens against each other if they are still the same
    if (Session::get($form.'_token') !== $data['token']) {
        return false;
    }

    return true;
}

I can set a session no problem but when I come to get it using verifyFormToken(), i get this error message

Can't use function return value in write context

which points to this line

if(!isset(Session::get($form.'_token'))){ 
  • 写回答

1条回答 默认 最新

  • donglian1982 2014-07-17 12:27
    关注

    you will have to define a variable as pass that to isset:

    $token = Session::get($form.'_token');
    if ($token !== NULL) { ... }
    

    or as you are using isset in your get method just do:

    if (Session::get($form.'_token') !== NULL) { ... }
    

    EDIT**

    In this instance this would be fine, as session token will never be null, but as a session controller, a value may be set as NULL on purpose, or may not be set, so your get method needs to return a unique value to determine whether its set or not. i.e.

    define('MY_SESSION_NOT_SET',md5('value_not_set'));
    
    class Session
    {
        public static function init() {
           @session_start();
        }
    
        public static function set($key, $value) {
            $_SESSION[$key] = $value;
        }
    
        public static function get($key) {
            if (isset($_SESSION[$key]))
                return $_SESSION[$key];
            else
                return MY_SESSION_NOT_SET;
        }
    
        public static function destroy() {
            unset($_SESSION);
            session_destroy();
        }
    }
    
    if (Session::get($form.'_token') === MY_SESSION_NOT_SET) { ... }
    

    something like that would be more beneficial.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)