首页 > 代码库 > php 依赖注入

php 依赖注入

对于依赖注入 我现在的理解是把一个方法当成一个变量放进另一个方法的形参里

 

<?php
class Factory {
    public static function getDb(){
        return new Db();
    }
}

class Db {
    public static function query($sql){
        echo $sql;
    }
    public static function querys($sql){
        echo $sql."s";
    }
}


class example {
    private $_db;
    function getList(){
        $this->_db->query("123");//这里具体sql语句就省略不写了
    }
    //从外部注入db连接
    function setDb($connection){
        $this->_db = $connection;
    }
}
//调用
$example = new example();
$example->setDb(Factory::getDb());//注入db连接
$example->getList();

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 简单点

<?php
class email {
    public static function sendemail(){
        echo "发送邮件";
    }
}

class sms {
    public static function sendsms(){
        echo "发送短信";
    }
}


class example {
    private $_send;
    function setSend($send_function){
        $this->_send = $send_function;
    }
}

$example = new example();
$example->setSend(sms::sendsms());

example好比注册的类,注册成功后想发送短信就

$example = new example();
$example->setSend(sms::sendsms());

想发送邮件就

$example = new example();
$example->setSend(email::sendemail());

 

php 依赖注入