duanaoou4105 2012-12-16 14:24
浏览 53
已采纳

CakePHP - 无法在视图中获取会话变量

In ProjectsController.php I'm setting a session variable as I'd like that info to be accessible in ALL controllers, models and views:

$this->Session->write('Project.title', $this->Project->title);

Now, when I try access it from Projects view, like this:

        <p>Project: <strong>
        <?php if (isset($session->read('Project.title'))): 
            $session->read('Project.title');
        ?>
        <?php else: ?>
            Not selected
        <?php endif; ?>
        </strong></p>       

I'm getting the following error:

Fatal error: Can't use method return value in write context 

Which refers to the second line of above code.

I've been through CakePHP documentation and also searched SO, what am I doing wrong here?

Thanks!

EDIT:

I've also tried using:

$this->Session->read('Project.title')

resulting in the same error message.

  • 写回答

2条回答 默认 最新

  • dongyi1524 2012-12-16 14:27
    关注

    You should do what PHP tells you once in a while :) The error message is pretty clear. You cannot use isset() and empty() this way. They only work with variables direcly, not methods. So use

    <?php if ($this->Session->check('Project.title')) {
        echo $this->Session->read('Project.title');
    } ?>
    

    as documented in the cookbook

    you could also do

    <?php
    $title = $this->Session->read('Project.title');
    if ($title) {
        echo $title;
    } ?>
    

    or even

    <?php if ($title = $this->Session->read('Project.title')) {
        echo $title;
    } ?>
    

    the last one is not cakephp coding convention, though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问