【问题标题】:Laravel 4 Class Function call error using $this使用 $this 的 Laravel 4 类函数调用错误
【发布时间】:2016-04-11 21:19:54
【问题描述】:

我想使用 addMenu 和 menu 功能,但出现此错误:

Using $this when not in object context

我做错了吗?还是有其他方法可以调用这些函数?
我的代码:

class Documentation {
    protected $app;
    protected $menu = [];

    public function __construct(Application $app){
        $this->app = $app;
        $this->addMenu(["Hello world"]);

    }
    public static function addMenu($item){
        $this->menu[] = $item;
    }
    public static function menu(){
        return $this->menu;
    }
}

【问题讨论】:

    标签: php class laravel laravel-4


    【解决方案1】:

    您不能在 static 上下文中使用 $this 变量。在您的情况下,我建议您更改功能并摆脱 static 关键字

    class Documentation {
        protected $app;
        protected $menu = [];
    
        public function __construct(Application $app){
            $this->app = $app;
            $this->addMenu(["Hello world"]);
        }
    
        public function addMenu($item){
            $this->menu[] = $item;
        }
    
        public function menu(){
            return $this->menu;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 2013-06-10
      • 2015-09-25
      • 2017-06-24
      • 2014-04-29
      相关资源
      最近更新 更多