Laravel: Get access to class-variable from public static function (basic oop issues)

laravel, oop, php

Solution

Static methods do not have access to `$this`. `$this` refers to an instantiated class (an object created with a `new` statement, e.g. `$obj = new ContentController()`), and static methods are not executed within an object.

What you need to do is change all the `$this` to `self`, e.g. `self::$text` to access a static variable defined in your class. Then you need to change `public $text = '';` to `public static $text = '';`

This is why static methods/variables are bad practices most of the time...

Not an expert at Laravel, but I'm sure you don't need to use static methods to pass variables into templates... If that is the case, I'm staying the hell away from Laravel...

Problem

EDIT In the meantime this question is been visited a few times. Just to share what I´ve learned with the help of stackoverflow and other resources I´d not recommend using the technique I was asking for. A cleaner way is to attach a variable containing the database-text within the controller: ``` $txt = Model::find(1); return view('name', array('text' => $txt->content); ``` Now you can access text in your view like so ``` {{ $text ?? 'Default' }} ``` But if you´re currently also hustling with basic oop and/or mvc architecture read on. Maybe it helps :-) ORIGINAL QUESTION I´m trying to output some text loaded from db. This is my setup: View: ``` {{ ContentController::getContent('starttext') }} ``` Controller: ``` class ContentController extends BaseController { public $text = ''; public static function getContent($description) { $content = Content::where('description', $description)->get(); $this->text = $content[0]->text; return $this->text; } } ``` I was trying various ways to declare a class variable and access it in my function but I always end up with: Using $this when not in object context tbh I think I lack some basic oop knowledge :-D

Original source