Laravel doesn't remember class variables

2019-08-14 17:15发布

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!

2条回答
对你真心纯属浪费
2楼-- · 2019-08-14 17:59

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;
}
查看更多
相关推荐>>
3楼-- · 2019-08-14 18:04

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

查看更多
登录 后发表回答