简体   繁体   中英

Laravel doesn't remember class variables

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!

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;
}

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. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM