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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应