douxian0008 2013-12-19 21:32 采纳率: 0%
浏览 262
已采纳

Laravel私有变量在Controller中的两个方法之间共享

How to use private variable in Laravel Controller, and share that variable value between two methods. (Set it in one use it in another).

  • 写回答

2条回答 默认 最新

  • douyinliu8813 2013-12-19 21:38
    关注

    You're talking about one single controller, right? So I'll assume that this what you mean:

    class ControllerController extends Controller {
    
        private $variable;
    
        public function __construct($whatever)
        {
            $this->variable = $whatever;
        }
    
        public function method1($newValue)
        {
            $this->variable = $newValue;
        }
    
        public function method2()
        {
            return $this->variable;
        }
    
    }
    

    If you are doing thing in the same request, you can

    $this->method1('newvalue');
    
    echo $this->method2();
    

    And it will print newvalue.

    If you are doing it between requests, you need to remember that your application ends after a request a restart in a new one, so you'll need to store it somewhere, like in a Session variable:

    Session::put('variable', $newvalue);
    

    and then

    Session::get('variable');
    

    Or you can redirect with the value you need to get back in your method:

    Redirect::to('posts')->with('variable','this is a new value');
    

    And in the second

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

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 MATLAB四叉树处理长方形tif文件
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了