Laravel doesn't remember class variables

2019-08-14 17:59发布

问题:

I have a class in Laravel with a class variable that holds and object

class RegisterController extends Controller {
    public $company;

When i set the variable in my index method all goes well

public function index($id = null) {
    $this->company = new Teamleader\Company;

When I try to access $this->company from another method it returns null

This is my full code

class RegisterController extends Controller {

    public $company;

    public function index($id = null)
    {
        $this->company = new Teamleader\Company;

        // returns ok!
        dd($this->company);
        return view('register.index');
    }

    public function register()
    {
        // returns null
        dd($this->company);
    }

}

Am I missing something? Thank you!

回答1:

In Laravel 5 you can inject a new instance of Teamleader\Company into the methods you need it available in.

use Teamleader\Company;

class RegisterController extends Controller {

    public function index($id = null, Company $company)
    {
        dd($company);
    }

    public function register(Company $company)
    {
        dd($company);
    }
}

For Laravel <5 dependency inject into the constructor.

use Teamleader\Company;

class RegisterController extends Controller {

    protected $company;

    public function __construct(Company $company)
    {
        $this->company = $company;
    }

    public function index($id = null)
    {
        dd($this->company);
    }

    public function register()
    {
        dd($this->company);
    }
}

Dependency injection is better than manual invocation as you can easily pass a mock object to this controller during testing. If you're not testing, maybe someone else will be in the future, be kind. :-)



回答2:

You are not __constructing() the class, you are just assigning variable inside a function inside a class, which means it is encapsulated into that function inside that class.

So if you would like to make $this->company global in class, you could use

public function __construct() {
 $this->company = new Teamleader\Company;
}