Blogger Information
Blog 14
fans 0
comment 0
visits 8620
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
依赖注入 2018.05.23 15:55
弗洛加特的博客
Original
695 people have browsed it

实例

class Spring
{
    public function flower()
    {
        return '春天花会开';
    }
    public function bird()
    {
        return '鸟儿自由自在';
    }
}
//依赖注入:把当前依赖的对象当做参数注入到当前的类中,简称依赖注入
//构造方法依赖注入
class Season1
{
    private $spring;
    public function __construct(Spring $spring)
    {
        return $this->spring=$spring;
    }
    public function getSeason()
    {
        return '我们喜欢春的美,因为:'.$this->spring->flower().','.$this->spring->bird();
    }
}

$spring = new Spring();
$season1 = new Season1($spring);
echo $season1->getSeason();
echo '<hr>';

//普通方法依赖注入
class season2
{
    public function getSeason(Spring $spring)
    {
        return '我们喜欢春的美,因为:'.$spring->flower().','.$spring->bird();
    }
}
$spring = new Spring();
$season2 = new Season2();
echo $season2->getSeason($spring);

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!