Laravel忘记了类变量 [英] Laravel doesn't remember class variables

查看:65
本文介绍了Laravel忘记了类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Laravel中有一个带有可容纳对象的类变量的类

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;

当我尝试通过另一种方法访问$ this-> company时,它返回

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

这是我的完整代码

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!

推荐答案

在Laravel 5中,您可以将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);
    }
}

将Laravel< 5依赖项注入到构造函数中.

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

这篇关于Laravel忘记了类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆