在Laravel 4中访问作为依赖对象的对象

时间:2014-09-10 23:59:39

标签: php laravel laravel-4

我需要帮助解决问题。这是Laravel 4.2,它来自博客,没有办法联系作者或发表评论..

http://vegibit.com/what-is-the-ioc-container-in-laravel/

有人可以给我一个如何使用对象文字表示法访问其示例中的依赖对象的示例。

$myCar = App::make('Car');

所以我想访问Bridgestone对象的tread属性。

echo $myCar->Tire->Bridgestone()->tread; 

这不起作用,但这说明了我正在尝试做的事情。我正在尝试打印“性能”

谢谢....

1 个答案:

答案 0 :(得分:1)

变量受到保护,因此请尝试添加返回注入对象的公共函数:

class Car {
    protected $tire;
    protected $engine;
    public function __construct(Tire $tire, Engine $engine) {
        $this->tire = $tire;
        $this->engine = $engine;
    }

    public function tire()
    {
        return $this->tire;
    }
}

class Tire {
    protected $bridgestone;
    public function __construct(Bridgestone $bridgestone) {
        $this->bridgestone = $bridgestone;
    }

    public function bridgestone()
    {
        return $this->bridgestone;
    }
}

您对胎面的要求将是:

echo $car->tire()->bridgestone()->tread;