duangutang3940 2014-09-27 15:18
浏览 141
已采纳

Laravel对象在页面之间持久化

Here's my sample code.

class A {
  public function foo(){

 }

 public function bar(){
 }
}



class B {

  $one;
  function here(){
    $this->one = new A();
    $this->one->foo();
    return View::make("route1"); //This is ok, no problems
  }

  function there(){
    $this->one->bar(); //ERROR: Call to a member function bar() on a non-object
  }
}

My routes

Route::get("/one", B@here);
Route::get("/two", B@there);

Please these just show a sample. Its not the code proper.

When the first Route is called all is ok, and the corresponding page is loaded. Now on a button click which now requests the second page that error is thrown...

//Call to a member function bar() on a non-object

Its obvious the cause for this and I have been trying to see if Laravel offers a way to persist objects in between page calls and if someone can please help.

Thanks

  • 写回答

2条回答 默认 最新

  • dongshadu2546 2014-09-27 15:38
    关注

    There is no nice way to store objects between page loads and really you would never want to do that anyway. A possible solution would be to add your dependency in the class constructor so it available throughout your class like this:

    class A {
        public function foo(){}
        public function bar(){}
    }
    
    class B {
        protected $one;
    
        public function __construct(A $one)
        {
            $this->one = $one;
        }
    
        public function here()
        {
            $this->one->foo(); // Available
        }
    
        public function there()
        {
            $this->one->bar(); // Available
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型